Scale image to full page, keeping aspect ratio

I have an image and want to scale it to the full page size. I know, I can use \includegraphics[width=\textwidth]{...} to scale an image to the full page width (or \rotatebox{90}{\includegraphics[height=\pagewidth]{...}} in case the image needs to be turned 90 degrees). But the problem is that my images then use more space than the height of the page.

I have also tried to do \includegraphics[height=\textheight] and actually that also worked, but this opens two problems:

1. I have to guess for each image whether the height or the width will be the limiting factor and
2. there is no more space for the image caption. This means, I get an overfull box unless I reduce the height manually, but I have to guess the factor for each image.

What I'd really appreciate is to say that I want such an image to be scaled as much as possible, keeping the aspect ratio but small enough that the caption also fits into the page. Is there a good way to achieve this?

I am using the scrbook class, should that make any difference.

• See my edit yo avoid caption room, I have missed on the first answer. – Tarass Mar 15 '18 at 10:55

\documentclass{scrbook}
\usepackage{lscape,graphicx,ifthen,calc}

\newsavebox{\image}
\newlength{\MyLgth}

\def\CaptionRoom{30pt} % Empirically set

\makeatletter
\newcommand*{\DivideLengths}[2]{%
\strip@pt\dimexpr\number\numexpr\number\dimexpr#1\relax*65536/\number\dimexpr#2\relax\relax sp\relax
}
\makeatother

\newcommand{\SetMyLght}[1]{%
\sbox{\image}{\includegraphics[width=\linewidth]{#1}}%
\ifthenelse{\lengthtest{\ht\image>\textheight}}{%
\setlength{\MyLgth}{%
\DivideLengths{\textheight-\CaptionRoom}{\ht\image}\linewidth}%
}{%
\setlength{\MyLgth}{\linewidth}%
}%
}

\newcommand{\MyImage}[2][]{%
\sbox{\image}{\includegraphics{#2}}%
\ifthenelse{\lengthtest{\wd\image>\ht\image}}{%
\begin{landscape}%
\SetMyLght{#2}%
\begin{figure}[!ht]
\hfill\includegraphics[width=\MyLgth]{#2}\hfill\strut%
\caption{#1}
\end{figure}
\end{landscape}
}{%
\SetMyLght{#2}%
\begin{figure}[!ht]
\hfill\includegraphics[width=\MyLgth]{#2}\hfill\strut%
\caption{#1}
\end{figure}
}
}

\begin{document}

\MyImage[Why science teachers should not be given playground duty.]{sc-teacher}%

\MyImage[The Monkey selfie.]{monkey-selfie}

\end{document}