Here is a quick fix. THE MWE should produce three identical images and one smaller image. Note that \includelimit only supports size changes.
BTW, this also answers the linked question. Also, do not use \dimen0 with \includegraphics.
\documentclass{standalone}
\usepackage{graphicx}
\newcommand{\includelimit}[2][]% will get bad results with [rotate]
{\bgroup
\sbox0{\includegraphics{#2}}%
\sbox1{\includegraphics[#1]{#2}}%
\dimen1=\ht0
\ifdim\ht1<\dimen1 \dimen1=\ht1\fi
\dimen2=\wd0
\ifdim\wd1<\dimen2 \dimen2=\wd1\fi
\includegraphics[width=\dimen2, height=\dimen1]{#2}%
\egroup}
\begin{document}
\includegraphics{example-image}
\includelimit[width=20cm]{example-image}
\includelimit[height=20cm]{example-image}
\includelimit[scale=0.5]{example-image}
\end{document}

This shows how to replace \includegraphics with the new version. I do NOT recommend this since it no longer supports all the keywords.
\documentclass{standalone}
\usepackage{graphicx}
\let\oldincludegraphics=\includegraphics
\renewcommand{\includegraphics}[2][]% will get bad results with [rotate]
{\bgroup
\sbox0{\oldincludegraphics{#2}}%
\sbox1{\oldincludegraphics[#1]{#2}}%
\dimen1=\ht0
\ifdim\ht1<\dimen1 \dimen1=\ht1\fi
\dimen2=\wd0
\ifdim\wd1<\dimen2 \dimen2=\wd1\fi
\oldincludegraphics[width=\dimen2, height=\dimen1]{#2}%
\egroup}
\begin{document}
\oldincludegraphics{example-image}
\includegraphics[width=20cm]{example-image}
\includegraphics[height=20cm]{example-image}
\includegraphics[scale=0.5]{example-image}
\end{document}
scaleat all? – egreg Jul 15 '21 at 12:35scalevery rarely, but I would like the solution to be able to avoid upsizing of any image over its natural size also if I usescaleor any other way to resize an image (at least with\includegraphics). – mmj Jul 15 '21 at 12:56provided by a user. You may want to keep images within certain dimensions, except if they are smaller than the allotted space.
In that case, you should check the actual dimensions of the image to be inserted and then decide which
\includegraphicssetup to apply.See https://tex.stackexchange.com/a/185272/161015
– Simon Dispa Jul 15 '21 at 13:21