44

With \includegraphics I can give the width of the resulting image (which would be scaled).

How can I give a maximum width of the image? That is, if the original is smaller than X, I'd like to keep the smaller image, if the image is larger than X, then the image width should be X.

Using pdflatex/graphicx.

Martin Scharrer
  • 262,582
topskip
  • 37,020

3 Answers3

37

For more exotic requirements adjustbox or resizebox are useful but you don't really need any additional commands for this (other than a local command just to access @ commands more easily)

\documentclass{article}

\usepackage{graphicx}
\makeatletter
\def\maxwidth#1{\ifdim\Gin@nat@width>#1 #1\else\Gin@nat@width\fi}
\makeatother

\begin{document}

\includegraphics[width=\maxwidth{1in}]{image}

\includegraphics[width=\maxwidth{1cm}]{image}

\end{document}
David Carlisle
  • 757,742
  • 17
    It would have been even greater if the person who wrote the graphics package had exposed \Gin@nat@width by a local definition of \width as for other latex2e box commands to save needing the \makeatletter dance. Now, who was that.... – David Carlisle Dec 10 '12 at 11:02
  • 2
    @DavidCarlisle: I had the same thought when I studied graphics/x while writing adjustbox. There I provide the original width as \width. – Martin Scharrer Feb 02 '13 at 08:14
18

The adjustbox provides a max width key just for this purpose. If the package is loaded with the export option this key and most others can also be used for \includegraphics.

Here the content is only resized if its current size is larger than the given width. It works basically the same way as the code in David Carlisle's answer. If the \adjincludegraphics macro is used the original width can directly be accessed as \width. Note that this feature is not enabled for \includegraphics by the export option. However this can be done by making \includegraphics using \adjincludegraphics instead using \let\includegraphics\adjincludegraphics after loading adjustbox.

\documentclass{article}

\usepackage{mwe}% just for the example images
\setlength{\parindent}{0pt}

\usepackage[export]{adjustbox}% 'export' allows adjustbox keys in \includegraphics

\begin{document}

\hrule% to see \linewidth

\includegraphics[max width=\linewidth]{example-image-1x1}

\includegraphics[max width=\linewidth]{example-image-a4}

% With \adjincludegraphics (or \adjustimage) you can also use the original width as \width:
\adjincludegraphics[width=\ifdim\width>\linewidth \linewidth\else\width\fi]{example-image}

\end{document}
Martin Scharrer
  • 262,582
15
\documentclass{article}
\usepackage[demo]{graphicx}
\newlength\MaxWidth \newsavebox\IBox
\MaxWidth=100pt

\newcommand*\IncludeGraphics[2][]{%
  \sbox\IBox{\includegraphics[#1]{#2}}%
  \ifdim\wd\IBox>\MaxWidth \resizebox{\MaxWidth}{!}{\usebox\IBox}%
  \else\usebox\IBox\fi}

\begin{document}

\includegraphics{image}

\IncludeGraphics{image}

\IncludeGraphics[width=50pt]{image}

\end{document}

enter image description here