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}
maxwidth
in ConTeXt :)adjustbox