[Tex/LaTex] How to take figure width=\linewidth OR height=\pageheight

floatsheightwidth

I want to include figures such that either width or height is used to adjust the document on the page.
There are about 5\% of images where the height is dominating such that width=\linewidth causes overful.
In such a case, I would like to adjust by height=\pageheight.
Pseudocode

\documentclass{article}
\usepackage{graphicx}
\begin{document}
\begin{figure}
  % Make the decision here primarily by width; if overful, then height. 
  \includegraphics[width=\linewidth OR height=\pageheight]{1.jpg}
\end{figure}
\end{document}

TeXLive: 2016
OS: Debian 8.5

Best Answer

Just let the graphicx package have its way:

\documentclass{article}
\usepackage{graphicx}

\usepackage[showframe]{geometry} %just to visualise the boarder

\begin{document}

\noindent\includegraphics[width=\textwidth,height=\textheight,keepaspectratio]{example-image-golden}

\newpage

\noindent\includegraphics[width=\textwidth,height=\textheight,keepaspectratio]{example-image-golden-upright}

\end{document}

enter image description here