[Tex/LaTex] Trim image by number of pixels

cropdimensionsgraphics

Is it possible to trim an image by a certain number of pixels rather than a length?

I have a set of images that I'm including, and in one figure, a trim of 135 on the bottom works nicely, but a second version of the same images that has undergone some image processing got saved with a different DPI (not a different size), so the same trim appears to trim them quite differently.

However, both sets of images are 512×384, so is it possbile to just specify a trim in terms of image pixels, e.g. 100px? Thanks.

Best Answer

(Summarising the comments as an answer.)

pdfTeX will work with px units, but you have to set these up appropriately using \pdfpxdimen. This is the physical width of one pixel, and has default value of 1 bp, meaning that images initially are assumed to be 72 dpi. \pdfpxdimen is a low-level dimen primitive, and so is best set using \dimexpr:

\pdfpxdimen=\dimexpr 1 in/<dpi>\relax

where <dpi> is the resolution of the image.

With that set correctly, you can then use \includegraphics as normal, adding px to the values used by the trim (or other) key to get the right result.

As an example, consider the two images

600 dpi

and

72 dpi

which have the same pixel size but different resolution. Using the LaTeX file

\documentclass{standalone}
\usepackage{graphicx}
\begin{document}
\setlength\fboxsep{0 pt}
\pdfpxdimen=\dimexpr 1 in/600\relax
\includegraphics[clip,trim=0 100px 200px 100px]{Figure-a} % 600 dpi
\pdfpxdimen=\dimexpr 1 in/72\relax
\includegraphics[clip,trim=0 100px 200px 100px,scale = 0.12]{Figure-b} % 72 pdi
\end{document}

results in the output file

result

which shows the result of the trimming - both are the same. (I've scaled the second image so that the two are printed the same size by pdfTeX.)