‘Fill’ image within a box while maintaining aspect ratio

adjustboxfillgraphicsscale

I want to specify a box with certain dimensions, say \textwidth by \textheight, and then "fill" it with an image such that the image aspect ratio is maintained, there is no white space in the box, and any excess part of the image is cropped. Image aspect ratio can be any value.

If it were a Microsoft Windows desktop wallpaper it would be the "fill" setting.

To achieve the same thing with CSS one would use background-size: cover; see interactive example

I have already looked at the documentation of graphicx and adjustbox and found no answer, but perhaps I missed something.

It is also necessary to specify the anchor point, e.g. the bottom left corner of the image should coincide with the bottom left corner of the box.

The ideal interface would be something like \fillimage[width=\textwidth,height=\textheight,anchor=bottom left]{example-image}

Update: I now have half of the problem solved. See MWE below. Note how each of the images is cropped to fit.

Remaining problems:

  • controlling the "anchor" location properly
  • having to manually specify whether the image is too wide or too tall
\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[x=\textwidth,y=\textheight]
    \clip (-0.5,-0.5) rectangle (0.5,0.5);
    \node[inner sep=0pt,anchor=center] (0,0) {\includegraphics[height=\textheight,keepaspectratio]{example-image-golden}};
\end{tikzpicture}

\begin{tikzpicture}[x=\textwidth,y=\textheight]
    \clip (-0.5,-0.5) rectangle (0.5,0.5);
    \node[inner sep=0pt,anchor=center] (0,0) {\includegraphics[width=\textwidth,keepaspectratio]{example-image-golden-upright}};
\end{tikzpicture}


\end{document}

MWE

Best Answer

Using overzoom in tcolorbox can sometimes also be helpful

Here is a grid image which might help to figure out what is happening

enter image description here

\documentclass{article}
\usepackage[most]{tcolorbox}

\begin{document}

\section{Original image set to height 10cm}

\includegraphics[height=10cm]{grid100.jpg}

\section{Overzoom at height 11cm width 5cm}

By default the focus is on the middle part

\begin{tcolorbox}[enhanced,width=5cm,height=11cm,interior style={fill overzoom image=grid100.jpg}]
\end{tcolorbox}

\section{Overzoom at height 2cm width 15cm}

\begin{tcolorbox}[enhanced,width=15cm,height=2cm,interior style={fill overzoom image=grid100.jpg}]
\end{tcolorbox}

\section{ starred version of the key to pass options to includegraphics and so use trim or viewport}

\begin{tcolorbox}[enhanced,width=5cm,height=11cm,interior style={fill overzoom image*={trim=4cm 4cm 0cm 0cm}{grid100.jpg}}]
\end{tcolorbox}

\begin{tcolorbox}[enhanced,width=15cm,height=2cm,interior style={fill overzoom image*={viewport= 5cm 1cm 10cm 10cm}{grid100.jpg}}]
\end{tcolorbox}


\end{document}

enter image description here