# Always scale and clip background image so it fills the page

I have learned from other answers how to use an image file as background and make it transparent. Since my background files do not necessarily have the exact page dimensions (they are provided by users), I want to scale and clip them to fit.

I have found, however, that using

\includegraphics[width=\paperwidth,height=\paperheight,keepaspectratio,clip]{#1}


does not always scale correctly; landscape-oriented images are scaled so widths fit and then not clipped at all if they are very flat, so a white bar remains. For example, this is using a 1600x750 image on a US Letter landscape page:

\documentclass[landscape]{article}
\usepackage{eso-pic,graphicx}
\pagestyle{empty}
\begin{document}
\put(0,0){%
\parbox[b][\paperheight]{\paperwidth}{%
\includegraphics[width=\paperwidth,height=\paperheight,keepaspectratio,clip]{test.png}%
}%
}%
}%
\phantom{lorem ipsum}
\end{document}


How can I tell includegraphics to always scale the shorter dimension to fit?

-

As far as I can tell, you can't. adjustbox, always worth a look, does not seem to offer the necessary option(s), either.

Luckily, we can hack it. Observe that

\includegraphics[width=\paperwidth,keepaspectratio,clip]{img}


works well for portrait images -- scaling them so the width fits and clip -- and the opposite

\includegraphics[height=\paperheight,keepaspectratio,clip]{img}%


works for landscape images. So we can choose the correct version according to image dimensions which version to use:

\settoheight\imageheight{\includegraphics{img}}%
\settowidth\imagewidth{\includegraphics{img}}%
\ifthenelse{\dimtest{\imageheight}{>=}{\imagewidth}}{%
\includegraphics[width=\paperwidth,keepaspectratio,clip]{img}%
}{%
\includegraphics[height=\paperheight,keepaspectratio,clip]{img}%
}%


Note that this requires package xifthen. The example then ends up compiling to:

I have not figured out yet how to choose a well-defined part of the image, say the middle part, when clipping; it seems to work from the left resp. the bottom by default. Also, the clipped image seems to produce Overful \hbox warnings.

-