[Tex/LaTex] How to rotate image 90 if height overful

adjustboxconditionalsgraphicsrotating

I think the approach can be with adjustbox but not sure.
Pseudocode:

  • If height overfull, turn the image 90 degree clockwise, apply all images the width constraint now
  • Do not pass max width (= \linewidth) in any case.

In other words, preudocode

  • If the image is too high originally, rotate it 90 so the biggest dimension will now be width. Scale the width to width=\linewidth.

Pseudocode

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\begin{figure}
  % If image height overfull, rotate the image 90 degree clockwise. Apply now to it width constaint. 
  \includegraphics[if HEIGHT overfull, rotate 90 degree clockwise; width=\linewidth]{1.jpg}
\end{figure}
\end{document}

Best Answer

Here is a general approach that you can follow:

\documentclass{article}

\usepackage{graphicx}
\newsavebox{\imgbox}

\begin{document}

\begin{figure}
  \savebox{\imgbox}{% Store image in a box
    \includegraphics[height=<h>,width=<w>,keepaspectratio]{example-image}}%
  \ifdim\ht\imgbox > <H>
    % Do something to the box
  \else
    \usebox{\imgbox}%
  \fi
\end{figure}

\end{document}

In essence, you want to condition on the size of the included image. If it's too tall (or too wide), you may want to manipulate it otherwise. So, you store the image in a box (say, \imgbox), and then you can test the height - \ht\imgbox - or the width - \wd\imgbox against some other dimensions.


Specific to your application, you could do the following:

\begin{figure}
  \savebox{\imgbox}{% Store image in a box
    \includegraphics[height=\textheight,width=\linewidth,keepaspectratio]{example-image}}%
  \ifdim\ht\imgbox > \textheight
    \resizebox{\linewidth}{!}{\rotatebox{90}{\includegraphics{example-image}}}%
  \else
    \usebox{\imgbox}% Use resized image as-is
    % \resizebox{\linewidth}{!}{\usebox{\imgbox}}% ...maybe resize to fit width
  \fi
\end{figure}