Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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}
  \AddToShipoutPicture*{%
    \put(0,0){%
      \parbox[b][\paperheight]{\paperwidth}{%
        \includegraphics[width=\paperwidth,height=\paperheight,keepaspectratio,clip]{test.png}%
      }%
    }%
  }%
  \phantom{lorem ipsum}
\end{document}

enter image description here

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

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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:

enter image description here

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.