Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scale image down, but not up in latex

Tags:

latex

I have a command which includes an includegraphics command - I can pass an image to my command, and it will do some standard formatting for me before actually including the image. Some of the images that I'm including via this command are smaller than \textwidth, while some are larger. I'd like to scale the larger images down to \textwidth, while not scaling the smaller images up - this means I can't just do

\includegraphics[width=\textwidth]{img}

Is there a way to specify a maxwidth? Or, can I get the width of the image somehow so I can do something like

\ifthenelse{\imagewidth > \textwidth}{%
    \includegraphics[width=\textwidth]{img}}{%
    \includegraphics{img}}
like image 571
Matt McMinn Avatar asked Sep 23 '08 17:09

Matt McMinn


1 Answers

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!

like image 134
ChrisN Avatar answered Sep 28 '22 14:09

ChrisN