# Cropping images to box

Is there any easy way in (Lua)LaTeX to crop an image to a specific bounding box, but only cropping on the one dimension which is too large for the box?

A solution to crop on the height could be the following:

\usepackage{adjustbox}

trim=0cm {0.5\height-6cm*\width/\pagewidth} 0cm {0.5\height-6cm*\width/\pagewidth},
keepaspectratio=true,
width=\pagewidth}
{image.jpg}


But I would like to crop on the dimension which is larger than the bounding box automatically.

Is there some package I have overlooked? It's kind of hard to believe I am the first wanting to do this?

The use case is a title page, but where I would like to be able to swap the image depending on the document. So in general I do not know the dimensions of the image in advance or the orientation. It has to be determined from LaTeX.

• Instead of clip=true, trim=... you can just use Clip=... (note the uppercase 'C'). Also keepaspectratio=true is only used if width and height are both used. – Martin Scharrer Dec 27 '18 at 10:43

Like this?

\documentclass{article}
\usepackage{graphics}

\newcommand{\fillbox}[3]% #1=width, #2=height, #3=filename
{\bgroup
\dimen1=#1\relax% store width into register
\dimen2=#2\relax% store height into register
\sbox0{\includegraphics[width=#1]{#3}}%
\ifdim\ht0>\dimen2
\dimen0=\dimexpr \ht0-\dimen2\relax
\else
\sbox0{\includegraphics[height=#2]{#3}}%
\ifdim\wd0>\dimen1
\dimen0=\dimexpr \wd0-\dimen1\relax
\else
\usebox0
\fi
\fi
\egroup}

\begin{document}
\noindent\fillbox{\textwidth}{0.2\textheight}{example-image}
\rule{\textwidth}{0.2\textheight}

\noindent\fillbox{0.4\textwidth}{0.5\textheight}{example-image}%
\rule{0.4\textwidth}{0.5\textheight}
\end{document}


• It works like intended - thank you very much. – Jonatan Hjul Jun 12 '18 at 6:45
• Honestly this deserves more upvotes. Thank you so much! – M.O. Apr 26 at 2:27