[Tex/LaTex] Scale (resize) large images (graphics) that exceed page margins

graphicslyxmarginsscaling

Background

A large number of screen captures have been scaled 300% at 288dpi. They appear correctly when embedded in OpenOffice, but not LyX.

Problem

Images that do not extend beyond the margins (small images) appear perfectly. Images that are too big extend beyond the margins.

Attempt #1

\setkeys{Gin}{width=1.0\textwidth} 

However, that code scales the smaller images to also fit the width, which is undesirable. (The smaller images become distorted.)

Attempt #2

Didn't attempt this, but it looks useful.

% Redefine includgraphics for avoiding images larger than the screen size
% If the size is not specified.
\let\py@Oldincludegraphics\includegraphics

\newbox\image@box%
\newdimen\image@width%
\renewcommand\includegraphics[2][\@empty]{%
  \ifx#1\@empty%
    \setbox\image@box=\hbox{\py@Oldincludegraphics{#2}}%
    \image@width\wd\image@box%
    \ifdim \image@width>\linewidth%
      \setbox\image@box=\hbox{\py@Oldincludegraphics[width=\linewidth]{#2}}%
      \box\image@box%
    \else%
      \py@Oldincludegraphics{#2}%
    \fi%
  \else%
    \py@Oldincludegraphics[#1]{#2}%
  \fi%
}

Source: http://svn.python.org/projects/external/Sphinx-1.0.5/sphinx/texinputs/sphinx.sty

Attempt #3

% Resize figures that are too wide for the page
\let\oldincludegraphics\includegraphics
\renewcommand\includegraphics[2][]{%
  \makeatletter%
  \def\maxwidth{\ifdim\Ginnatwidth>\linewidth\linewidth%
  \else\Ginnatwidth\fi}%
  \makeatother%
  \oldincludegraphics[width=\maxwidth]{#2}%

Packages

Using graphicx.

Other package suggestions are welcome.

Question

Without adding LaTeX code to every image that exceeds the margins, what can be done to resize just those images that are too big?

Example

The following image is an example of many, many images that must be scaled back to fit the page width:

Related

Best Answer

Using the adjustbox package with the export option which extends graphicx with several new keys you can now simply use the max width key which scales the image down to that width if it is larger but doesn't scale it at all if it is smaller the equal to it. There are also the related keys max height, max size (for both width and height) as well as min width, min height and min size.

In your case simply use the following code:

\includegraphics[max width=\linewidth]{<image file name>}

Note that you can't set max width etc. in a global way using \setkeys{Gin}{max width=...}. It is implemented in a different way as width. However, I'm planning to add a possibility for this as well.