tags:

views:

1928

answers:

2

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}}
A: 

After a few minutes of searching through CTAN manuals and Google results, I think I can safely say that what you want to do is either impossible or very hard. My only recommendation is that you have two commands, one for small images and one for large, or one command with an option.

There may be a way, but I leave it to other S.O. LaTeX wizards to provide a better answer.

Edit: I am wrong, see above.

Steve Johnson
I came to the same conclusion - although, I've gotten everything figured out except for how to get the width of the image, so I'm really hoping that I can get over that last hurdle.
Matt McMinn
+4  A: 

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!

ChrisN
I don't know how many times I looked at \settowidth and decided that it wouldn't work on images for some reason - thanks!
Matt McMinn