clip a image with relative coordinate

The problem is that you need to need to know how large the image is before you can apply a relative clip. The usual ways to do that are to use a savebox or use \phantom.

Using savebox:

\tikzset{mynode/.style={draw,solid,circle,inner sep=1pt}}
\usetikzlibrary{calc}

\usepackage{etoolbox}
\newbool{DEBUG}
\booltrue{DEBUG}
%\boolfalse{DEBUG}

\newsavebox{\tempbox}

\usepackage{mwe}% for example images

\begin{document}
\def\infilename{example-image}%
\savebox{\tempbox}{\includegraphics[width=5cm]{\infilename}}%
\fbox{
\begin{tikzpicture}[>=latex]
  \path (0,0) (\wd\tempbox,\ht\tempbox);% set bounding box
    \begin{scope}[x={\wd\tempbox},y={\ht\tempbox}]
        \clip (0.4,0.6) rectangle (0.5,0.7);
        \node[anchor=south west,inner sep=0] {\usebox\tempbox};
        \ifbool{DEBUG}{\small
            \draw[help lines,xstep=.1,ystep=.1] (0,0) grid (1.001,1.001);
            \foreach \x in {1,...,9} { \node [anchor=north] at (\x/10,0) {\x};}
            \foreach \y in {1,...,9} { \node [anchor=east] at (0,\y/10) {\y};}
        };
    \end{scope}
\end{tikzpicture}}

\end{document}

Using \phantom:

\documentclass{standalone}
\usepackage{tikz}
\tikzset{mynode/.style={draw,solid,circle,inner sep=1pt}}
\usetikzlibrary{calc}

\usepackage{etoolbox}
\newbool{DEBUG}
\booltrue{DEBUG}
%\boolfalse{DEBUG}

\usepackage{mwe}% for example images

\begin{document}
\def\infilename{example-image}
\fbox{
\begin{tikzpicture}[>=latex]
    \node[anchor=south west,inner sep=0] (image) {\phantom{\includegraphics[width=5cm]{\infilename}}};
    \begin{scope}[x={(image.south east)},y={(image.north west)}]
        \clip (0.4,0.6) rectangle (0.5,0.7);
        \node[anchor=south west,inner sep=0] {\includegraphics[width=5cm]{\infilename}};
        \ifbool{DEBUG}{\small
            \draw[help lines,xstep=.1,ystep=.1] (0,0) grid (1.001,1.001);
            \foreach \x in {1,...,9} { \node [anchor=north] at (\x/10,0) {\x};}
            \foreach \y in {1,...,9} { \node [anchor=east] at (0,\y/10) {\y};}
        };
    \end{scope}
\end{tikzpicture}}

\end{document}

cliped image

Tags:

Tikz Pgf