Scale image down, but not up in latex

I like an additional parameter for optionally scaling the image down or up a bit, so my version of \scalegraphics looks like this:

\newcommand\scalegraphics[2][]{%
    \settowidth{\imgwidth}{\includegraphics{#2}}%
    \setlength{\imgwidth}{\minof{#1\imgwidth}{\textwidth}}%
    \includegraphics[width=\imgwidth]{#2}%
}

To get the width of the image you can use this code:

\newlength{\imgwidth}
\settowidth{\imgwidth}{\includegraphics{img}}

You could use this in the document preamble to create a new command to automatically set the width:

\usepackage{graphicx}
\usepackage{calc}

\newlength{\imgwidth}

\newcommand\scalegraphics[1]{%   
    \settowidth{\imgwidth}{\includegraphics{#1}}%
    \setlength{\imgwidth}{\minof{\imgwidth}{\textwidth}}%
    \includegraphics[width=\imgwidth]{#1}%
}

and then, in your document:

\scalegraphics{img}

I hope this helps!

Tags:

Latex