# Shrink figure only when necessary?

I'm writing a report where I have generated and included several TikZ pictures which I also want to use in my beamer presentation. However, some of the pictures (but not all) which fit in the report are too large for the slides. Hence, I wonder if there is any package or macro which shrinks a figure if it is too large, but leaves it alone if it already fits.

If the answer only works for TikZ then that's fine. I don't mind shrinking texts and lines along with the entire figure.

-

The adjustbox package can be used to scale (or otherwise adjust) images or any other content, like a tikzpicture in several ways. You need the max size={<width>}{<height>} option in your case, which does exactly what you requested, i.e. only shrink the content if it is larger than the given width and/or height. It always keeps the aspect-ratio.

\usepackage{adjustbox}

% ..

\begin{tikzpicture}
% ..
\end{tikzpicture}


This is also possible for images. Here the same key can be used with \adjustimage:

\adjustimage{max size={..}{..}}{<imagefilename>}


which uses \includegraphics internally, but wraps it in a \adjustbox macro.

-
PS: A related question which I also solved with adjustbox is Scale included graphics to the higher ratio instead of the lower for given width, height. It is the other way around (scaling up if required) plus some more stuff (cropping). –  Martin Scharrer Oct 3 '11 at 8:25
Ah excellent. But why do you use .95\textwidth instead of the whole \textwidth? –  gablin Oct 3 '11 at 8:27
Just personal taste. The full text width sometimes looks a little wide. You can of course use \textwidth. Unfortunately the \textheight includes the title and sub-title (if present) as well. There heights are theme specific and so you have to guess the maximum usable height. –  Martin Scharrer Oct 3 '11 at 8:30
Ah. Well, so far none of my pictures are taller than they are wide. –  gablin Oct 3 '11 at 9:09
Thank you for the excellent package, Martin. Adjustbox saved me from long tinkering of the tikz picture size. –  user8478 Oct 10 '11 at 10:41

works also for images which are wrongly set to a width greater than the text width:

\documentclass{minimal}
\usepackage{graphicx}
\newsavebox\IBox
\let\Includegrfx\includegraphics
\renewcommand\includegraphics[2][]{%
\sbox\IBox{\Includegrfx[#1]{#2}}%
\ifdim\wd\IBox>\textwidth\resizebox{\textwidth}{!}{\usebox\IBox}\else
\usebox\IBox\fi}
\parindent=0pt % for demo
\begin{document}
\rule{\textwidth}{1pt}

\includegraphics[width=3\textwidth]{tiger}

\end{document}

-