[Tex/LaTex] How to trim / clip / crop graphics without trial and error

cropgraphics

Often I include graphics with the trim option. Everytime I have to start a trial and error search for the right values. Is it possible to do it more straight forward?

Best Answer

Sometimes the grid in the corner is to far away, when cropping to axis labels. So I made an update, where I add rectangles over the whole image. And I add an optional parameter to control how deep the rectangles are drawn.

The thick lines have a distance of 10mm, the thin ones of 2mm. This is independent of the image if no width or height argument is passed to the image.

\usepackage{tikz}

% Linen über Graphiken
\newcommand{\showgrid}[3][5]{%
    \providecommand{\griddepth}{#1}
    \resizebox{#2}{!}{%
        \begin{tikzpicture}[inner sep=0]
            % Bild laden
            \node[anchor=south west] (image) at (0, 0) {#3};
            % Linien einfügen
            \begin{scope}[red]
                % Äußere Schleife für dicke Rechtecke
                \foreach \iThick in {0, ..., \griddepth} {%
                    \path (image.north east) ++(-\iThick, -\iThick) coordinate(topright);
                    \draw[semithick] (\iThick, \iThick) rectangle (topright);
                    % Zwischen den Linien auffüllen
                    \ifnum\iThick<\griddepth
                        % dünne Rechtecke
                        \foreach \iThin in {1, ..., 4} {%
                            \path (image.north east) ++(-\iThick, -\iThick) ++(-\iThin/5, -\iThin/5) coordinate(topright);
                            \draw[very thin] (\iThick, \iThick) ++(\iThin/5, \iThin/5) rectangle (topright);
                        }
                    \fi
                }
            \end{scope}
        \end{tikzpicture}
    }
}

Call the macro with

\showgrid[6]{0.9\linewidth}{\color{lightgray}{\rule{20cm}{25cm}}}

On images it is still necessary to put the width from the image to the first argument of \showgrid.

\showgrid[1]{0.8\linewidth}{\includegraphics[clip, trim=20mm 34mm 8mm 16mm]{Test.pdf}}