[Tex/LaTex] Resize figures that are too high or too wide in LyX

dimensionsfloatsgraphicslyx

I would like to know how to define a preamble in Lyx to resize the width and the height if the figure is too wide or high.
I've already tried this:

\usepackage{graphicx}

% Determine if the image is too wide for the page.
\makeatletter
\def\ScaleIfNeeded{%
  \ifdim\Gin@nat@width>\linewidth
    \linewidth
  \else
    \Gin@nat@width
  \fi
}
\makeatother

% Resize figures that are too wide for the page.
\let\oldincludegraphics\includegraphics
\renewcommand\includegraphics[2][]{%
  \oldincludegraphics[width=\ScaleIfNeeded]{#2}
}

However, the problem is that the images that are too high continue to be too high, how could I adjust in the preamble both width and height?

Best Answer

You could add, to your LaTeX Preamble, the following:

\usepackage[export]{adjustbox}% http://ctan.org/pkg/adjustbox
% Resize figures that are too wide for the page.
\let\oldincludegraphics\includegraphics
\renewcommand\includegraphics[2][]{%
  \oldincludegraphics[#1,max width=\linewidth,max height=\textheight]{#2}
}

adjustbox allows to set the maximum width or maximum height of an included image and will modify it accordingly.

Note that if you set the maximum height to \textheight, an image included in a float with a caption might (will) not fit properly. You may have to consider something smaller than \textheight.

Related Question