[Tex/LaTex] \includegraphics: get the “scale” value of a figure whose size is expressed by “width”

boxescropincludegraphicsscale

Lets take this string:

\boxed{\includegraphics[width=0.4\textwidth]{FIGURE.pdf}}

that generates this figure:

enter image description here

Now lets say that I need to crop the blank margins of the figure keeping the figure's size.

I though I could do it with something like:

\boxed{\includegraphics[trim = L B R T, clip, scale=x]{FIGURE.pdf}}

Where L, B, R, and T are respectively the left, bottom, right and top trimming values and x is the scaling value.

The following example should better explain my question:

\boxed{\includegraphics[width=0.4\textwidth]{FIGURE.pdf}}\quad %
\boxed{\includegraphics[scale=0.238]{FIGURE.pdf}}\\

\boxed{\includegraphics[trim = 65 20 150 20, clip, width=0.4\textwidth]{FIGURE.pdf}}\quad %
\boxed{\includegraphics[trim = 65 20 150 20, clip, scale=0.238]{FIGURE.pdf}}

The previus code generates the following layout:

enter image description here

As you can see, using scale value instead of width lets me crop the figure keeping its size.

My question is: how can I get the exact (more or less) value of the scale parameter without go by trial and error? (My idea is to write some Emacs Lisp code to change the LaTeX code accordingly.)

I am open to any idea or suggestion.

Note. In most cases I use external software to crop my images (pdfcrop, briss etc.) but, sometimes, as in this case, they don't work so I need to trim manually.

Best Answer

All graphics are written to the PDF with a scale factor. When you specify a size the package just converts it to an appropriate scale factor. You can make \Gscale@box remember that scale factor for you (source). You can use the same \thelastscalefactor as many times as you need:

\documentclass{article}
\usepackage{graphicx}

\makeatletter
\let\ORG@Gscale@box\Gscale@box
\long\def\Gscale@box#1{%
  \xdef\thelastscalefactor{#1}%
  \ORG@Gscale@box{#1}}
\makeatother

\begin{document}

% Measuring the image without actually using it
\sbox0{\includegraphics[width=0.4\textwidth]{example-image}}\quad

\noindent % Using with the scale only
\fbox{\includegraphics[width=0.4\textwidth]{example-image}}\quad
\fbox{\includegraphics[scale=\thelastscalefactor]{example-image}}

\noindent
\fbox{%
  \makebox[0.4\textwidth][l]{% <-- trick to align without a tabular
    \includegraphics[trim = 65 20 150 20, clip, scale=\thelastscalefactor]{example-image}%
  }%
}\quad
\fbox{\includegraphics[trim = 65 20 150 20, clip, scale=\thelastscalefactor]{example-image}}

\end{document}

Output:

enter image description here

Related Question