# Resize images to half of text width only if too big for page margin

I want the images I'm using that exceed the page's text width to be scaled down to half the text width. Images that aren't wider than the text width don't need to be scaled. I have one markdown document that I'm converting to both html and pdf using pandoc.

The following code is in the preamble.

\usepackage{graphicx}
\makeatletter
\def\maxwidth{
\ifdim\Gin@nat@width>\linewidth
\linewidth
\else
\Gin@nat@width
\fi}
\makeatother
\let\Oldincludegraphics\includegraphics
\renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=\maxwidth]{#1}}


What syntax do I use to have maxwidth = x * \linewidth where x = .5 (or some other number)? This is the 5th line in code block.

-
–  Martin Scharrer Feb 2 '13 at 7:56

If you want to resize to half of \linewidth if it is wider than \linewidth then simply add a 0.5 in front of \linewidht in the then clause:

\usepackage{graphicx}
\makeatletter
\def\maxwidth{%
\ifdim\Gin@nat@width>\linewidth
0.5\linewidth
\else
\Gin@nat@width
\fi}
\makeatother
\let\Oldincludegraphics\includegraphics
\renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=\maxwidth]{#1}}


There should also be a % after the {, otherwise you get a space there, which might cause trouble.

Note that the adjustbox package adds a max width key and also allows to use the original width ad \width with \adjincludegraphics. For this see my answer to Includegraphics maximum width.

-

There is no need to redefine \includegraphics just

\maketletter
\setkeys{Gin}{width=\ifdim\Gin@nat@width>\linewidth
0.5\linewidth
\else
\Gin@nat@width
\fi}
\makeatother


In the preamble should cause all graphics inclusions to respect that scaling.

-

The following redefinition of \includegraphics allows for that:

\documentclass{article}
\usepackage{graphicx}% http://ctan.org/pkg/graphicx
\makeatletter
\let\old@includegraphics\includegraphics
\renewcommand{\includegraphics}[2][,]{%
\setbox9=\hbox{\old@includegraphics[#1]{#2}}%
\ifdim\wd9>\textwidth
\old@includegraphics[#1,width=.5\textwidth]{#2}%
\else
\old@includegraphics[#1]{#2}%
\fi%
}
\makeatother
\begin{document}
\noindent\rule{\textwidth}{1pt} \par
\noindent\includegraphics[width=.8\textwidth,height=50pt]{example-image-a}\par
\noindent\includegraphics[width=1.1\textwidth,height=50pt]{example-image-a} \par
\noindent\rule[1ex]{.5\textwidth}{1pt}
\end{document}

-