Stage 5 · Figures, tables and bibliography 35 / 48 ≈ 17 min read

Including Images in LaTeX: graphicspath, Scaling and Formats

Almost every image failure in LaTeX is one of four things: the engine cannot read that format, the search path is wrong, the scaling request is wrong, or the file name broke the lookup. This page covers the file search, the options that matter, the raster-versus-vector decision per engine, and the draft workflow that keeps a 60-figure document compiling in seconds.

    The three layers under includegraphics

    The graphicx package, part of the required graphics bundle that ships with every distribution, has one job: take a file, learn its natural size, apply a scaling request, and hand the result to the engine as a box. It does that in three layers, and knowing which layer failed tells you what to fix.

    The user layer is \includegraphics[⟨options⟩]{⟨file⟩} plus the declarations \graphicspath, \DeclareGraphicsExtensions and \DeclareGraphicsRule. The driver layer is the code that knows how this engine embeds this format: pdftex.def, luatex.def, dvipdfmx.def, dvips.def. graphicx picks the driver from the engine automatically, which is why the identical source can include a PDF under pdflatex and fail under latex plus dvips. The engine layer holds the primitives that actually place the bytes: \pdfimageresolution and the XObject inclusion code for pdftex, the special operators for the PostScript route.

    File loading is lazy: the graphic is read when its box is shipped out to the page, not when the command is read. That is why a "file not found" error can appear many lines below your \includegraphics, and why replacing a file on disk sometimes needs one more compile before the change shows up.

    There is no separate "insert picture" facility to click through: everything on the page came either from a file the engine could read, from a package that drew it (TikZ, pgfplots), or from an object some package converted. Keeping that model in your head turns image problems into a short checklist.

    How graphicx resolves a file name through graphicspath and the extension list, and which formats each TeX engine can read STEP 1 · FILE NAME RESOLUTION \includegraphics {sensor-layout} no extension given working directory tried first, always: the folder of the .tex file \graphicspath {{figures/}{plots/}} each entry needs its / first hit wins then read lazily, when the box ships to a page sensor-layout.pdf → .png → .jpg → .jpeg order set by \DeclareGraphicsExtensions STEP 2 · WHAT THE ENGINE CAN ACTUALLY READ format pdflatex lualatex xelatex → pdf latex + dvips .pdf native native native no .png .jpg native native native no .eps .ps convert first convert first convert first native .svg no engine reads it no engine reads it no engine reads it no .gif .bmp .tif .webp no no no no "convert first" is one Ghostscript step: convert once and commit the PDF, or let epstopdf / the svg package (Inkscape) do it during the run and carry a --shell-escape dependency with it.
    The file name is looked up in the working directory first, then in every graphicspath entry, and the first name built from the declared extension list wins.

    Which formats your engine accepts

    This is the most common cause of an error that reads like a missing file but is really an unsupported format. For pdflatex the safe set is PDF, PNG and JPEG. lualatex accepts the same three; xelatex in its normal PDF-output mode does too. Encapsulated PostScript is not one of them for any of the three.

    EPS is a page description, not an image stream, so putting it into a PDF means running it through Ghostscript first. Three ways to get there: convert once and commit the resulting PDF (the sturdy option), load the epstopdf package so the conversion happens during the run, or rely on your distribution's automatic conversion rule — which needs permission to write files and is exactly the kind of setting that differs between your laptop and a build server.

    The older latex → dvips → ps2pdf chain is the mirror image of that: there EPS is native and a PDF is the awkward input. This is the pdflatex-versus-xelatex trap people fall into when they inherit a thesis written for latex: a source full of .eps files needs every one of them converted, and the fix is a batch step, not an argument.

    SVG is supported by no engine directly. The svg package shells out to Inkscape during the run — so it needs --shell-escape and Inkscape on PATH — caches the produced PDF beside the source, and re-converts only when the SVG is newer. That is convenient locally and brittle on Overleaf or CI. Same advice for anything drawn in Inkscape, Illustrator or draw.io: export a cropped PDF and commit that. WebP, HEIC, BMP, GIF and TIFF are not loadable at all; convert them once with ImageMagick or GraphicsMagick and keep the converted file under version control.

    d_{\mathrm{eff}} = \frac{n_{\mathrm{px}}}{w_{\mathrm{print}}/25.4} = \frac{1200}{38/25.4} \approx 802\,\mathrm{ppi}
    d_{\mathrm{eff}} = \frac{n_{\mathrm{px}}}{w_{\mathrm{print}}/25.4} = \frac{1200}{38/25.4} \approx 802\,\mathrm{ppi}
    Effective resolution, not pixel count, is what a reader sees: 1200 px spread over 122 mm is a soft 250 ppi, which is the number to keep above roughly 200.

    graphicspath and the trailing slash rule

    \graphicspath takes a list of braced directories and is consulted only after the working directory itself has failed: \graphicspath{{figures/}{figures/plots/}{../shared/logos/}}. Each entry is {⁠directory name with trailing slash⁠}. The slash is not decoration — graphicx concatenates the string with the file name, so {figures} searches for figuresmy-plot.pdf and reports "file not found" for a file that is plainly there.

    Subdirectories are not searched recursively. {figures/} will not find figures/2024/run1.pdf. List every directory, or write the relative path in the argument, or use one flat directory with a naming convention such as fig-03-layout.pdf. The flat directory is what most long-lived projects converge on, because it stops a rename from breaking three chapters.

    The list is replaced, not extended: a second \graphicspath call overwrites the first. With per-chapter standalone builds the working directory also changes, which is the usual reason a figure appears in the whole document but not when chapter 4 is compiled alone; the answer is a path relative to the main file, or setting the path inside each chapter.

    Spaces in a directory name are a genuine break rather than a superstition: the search list is assembled into a file name and then handed to the operating system, and the space ends the first token. Rename the directory (an underscore costs nothing) or load grffile, which reimplements the lookup with spaces and additional suffix handling in mind. And on Windows write forward slashes in the paths: a backslash is TeX's escape character and will not survive the trip.

    \documentclass[a4paper]{article}
    \usepackage[T1]{fontenc}
    \usepackage[utf8]{inputenc}
    \usepackage{graphicx}
    \usepackage{caption}
    
    % Every directory is a braced group and MUST end with a slash.
    \graphicspath{{figures/}{figures/plots/}{../shared/logos/}}
    
    % Make the extension search deterministic (all four exist in pdftex.def's
    % default list; declaring it stops a stale .jpg winning over the .pdf).
    \DeclareGraphicsExtensions{.pdf,.png,.jpg,.jpeg}
    
    \begin{document}
    
    \begin{figure}[htbp]
      \centering
      % Relative width survives any page geometry; keepaspectratio is a
      % safety net for the case where a height is added later.
      \includegraphics[width=0.72\linewidth,keepaspectratio]{sensor-layout}
      \caption{Layout of the sensor board. Dashed lines mark the ground plane.}
      \label{fig:layout}
    \end{figure}
    
    Figure~\ref{fig:layout} shows the board at 72 percent of the line width.
    
    \end{document}

    Scaling: width, totalheight, scale and keepaspectratio

    The options worth knowing are width, height, totalwidth, totalheight, keepaspectratio, scale, angle and origin. scale=0.5 means "half of the natural size"; width=0.72\linewidth means "as wide as the current line, everything else in proportion". The second form is almost always the right one, because it keeps working when somebody changes the page geometry or moves the figure into a narrower box.

    Pick the reference length deliberately. \textwidth is the text block of the page, \columnwidth is the column the material sits in, and \linewidth is the width of the current line — equal to \textwidth in ordinary text, to the column width in two-column layout, and to the box width inside a minipage or a sub-figure. A figure sized against \textwidth inside a 0.45\textwidth minipage overflows by construction; inside a box, ask for \linewidth.

    Giving both width and height stretches the picture: nothing preserves the aspect ratio unless you add keepaspectratio, which then fits the graphic inside the requested rectangle. totalheight and totalwidth differ from height and width for rotated material because they measure the whole rotated box — with angle=90 that is the difference between a landscape plot that fits the page and one that swallows it.

    Where does the natural size come from? graphicx asks the driver: the media box for a PDF, the pixel count together with the resolution declared in the file for a PNG (\pdfimageresolution, 72 ppi when the file carries no pHYs chunk), the bounding box comments for EPS. That is why an unlabelled PNG export can appear four feet wide: 1200 px at 72 ppi is 42 inches. Either set the resolution in the exporter or always give a width.

    \frac{w^{\prime}}{w} = \frac{h^{\prime}}{h} \quad\Longleftrightarrow\quad \text{exactly one of } w^{\prime},\,h^{\prime}
    \frac{w^{\prime}}{w} = \frac{h^{\prime}}{h} \quad\Longleftrightarrow\quad \text{exactly one of } w^{\prime},\,h^{\prime}
    The professional habit is one dimension per figure, expressed as a fraction of the line it lives in.
    Three scaling requests applied to the same natural-size graphic, and which reference length each width option is measured against OPTION SET · SAME 400 x 300 REQUEST, SAME SOURCE FILE width=240, height=180, keepaspectratio fits inside the box, ratio kept, letterboxed. the safe default whenever a height is given at all width=240, height=180 stretched to both numbers: circles become ellipses. nothing warns you -- the log stays silent scale=0.6, height=180 scale applies to the natural size, then height wins. mixing scale with a dimension is how ratios break WHAT THE REFERENCE LENGTH MEANS ON THE PAGE \textwidth = whole text block of the page \columnwidth = the column you are in \linewidth = current line: \textwidth outside a box, the box width inside a minipage, subfigure or table cell inside a 0.45 \textwidth minipage, width=\textwidth overflows by construction
    One request, three option sets: a single dimension scales uniformly, width plus height distorts, keepaspectratio fits the graphic inside the box.

    draft and final: the fast compile loop

    \usepackage[draft]{graphicx} replaces every image with a framed box of exactly the right size containing the file name. Layout is preserved because the box has the same dimensions, and no pixels are decoded, so a document with sixty figures recompiles in seconds. final is the default and puts the real images back; \setkeys{Gin}{draft=true} and \setkeys{Gin}{draft=false} switch it mid-document, which you can wire to a draft/final option of your own class so a reviewer gets the fast build and the archive gets the real one.

    There is also quiet, which keeps the boxes but suppresses the printed names. Prefer it while you are checking page breaks: a long file name wraps inside the box and can change the box height, which is precisely the layout information you were trying to measure.

    This is not a cosmetic trick. Reading, decoding and re-embedding large raster files dominates the run time of a graphics-heavy document, so a draft pass lets you watch text reflow while you write, and one final pass before you send anything produces the real PDF. Because a draft box is not shipped as an image, the final PDF of a draft run is also small — handy for a fast upload, useless for a submission.

    In the final file, size is usually dominated by images rather than text. The pdftex knobs \pdfcompresslevel, \pdfobjcompresslevel and \pdfminorversion control how streams are stored; downsampling colour images afterwards with Ghostscript (gs -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress) is gentler on thin lines than re-exporting through a viewer, which silently discards the declared resolution and starts the stretching problem again from the other end.

    \documentclass[a4paper]{article}
    % draft draws correctly sized boxes with the file name in them and never
    % decodes a pixel: the fast pass for a document with many figures.
    % final is the default. Switch at run time with \setkeys{Gin}{draft=false}
    % -- and never load graphicx a second time with other options.
    \usepackage[draft]{graphicx}
    
    \begin{document}
    
    % trim = left bottom right top, and clip is what actually cuts.
    \includegraphics[width=0.5\textwidth,trim=12mm 4mm 30mm 6mm,clip]{noisy-export}
    
    % Page 3 of a multi-page PDF.
    \includegraphics[page=3,width=0.4\textwidth]{appendix-plots}
    
    % Fit inside a rectangle instead of stretching to it.
    \includegraphics[width=0.48\textwidth,height=0.2\textheight,keepaspectratio]{logo}
    
    % angle= rotates; origin=c rotates about the centre. totalheight is the
    % height of the ROTATED box, which is what you need for a landscape plot.
    \includegraphics[angle=90,origin=c,width=0.35\textheight]{long-chart}
    
    % The corner keys bbllx/bblly/bburx/bbury and natwidth/natheight are
    % dvips-only: the pdftex driver rejects them and tells you to use
    % viewport (or bb, which it treats as viewport).  Values are in bp,
    % measured from the lower left corner of the natural size.
    \includegraphics[width=0.4\textwidth,viewport=12 4 240 180]{raw-bitmap}
    
    % quiet: keep the file list out of the .log (a key, not a package option).
    \includegraphics[quiet,width=0.3\textwidth]{logo}
    
    % Tagged PDF / accessible output: the alternative text lives here, not
    % in the caption.
    \includegraphics[width=0.5\textwidth,
                     alt={A line chart of voltage against time},
                     actualtext={voltage falls from 5 V to 0.1 V in 12 s}]{decay}
    
    \end{document}

    Cropping: trim and clip, and the bounding box

    Matlab, Origin and gnuplot leave white margins around a plot, and that whitespace becomes part of the figure and defeats every alignment you attempt. graphicx handles it with trim=⟨left⟩ ⟨bottom⟩ ⟨right⟩ ⟨top⟩ together with clip: \includegraphics[width=0.6\textwidth,trim=10mm 5mm 25mm 5mm,clip]{plot}. The four lengths are in that order — left, bottom, right, top — which is inherited from TeX's own box specification and is the usual source of "I cropped the wrong edge". Crop a little first and look at the result.

    clip is what actually cuts. Without it the space is dropped from the dimensions of the box but the excluded region may still be painted by the driver, so you get an invisible overlap with the text next to it.

    For PDF sources you can also override the box entirely with bb=⟨llx⟩ ⟨lly⟩ ⟨urx⟩ ⟨ury⟩ and its companions bbunit= and bbangle=; trim/clip are then applied relative to that. For EPS, the %%BoundingBox comment can disagree with the ink actually drawn — %%HiResBoundingBox exists for that reason, and extractbb regenerates a truthful box after a conversion.

    Fixing the box at the source beats cropping in the document. matplotlib: savefig(..., bbox_inches='tight'). Any TikZ-only figure: compile it with the standalone class, which crops to the drawn content. Inkscape: resize the page to the drawing before exporting. Each of those deletes a trim line from your source, and a trim that nobody remembers is a maintenance liability the first time the plot is regenerated.

    \frac{w^{\prime}}{h^{\prime}} = \frac{s_{x}\,w}{s_{y}\,h} \ne \frac{w}{h} \qquad (s_{x} \ne s_{y})
    \frac{w^{\prime}}{h^{\prime}} = \frac{s_{x}\,w}{s_{y}\,h} \ne \frac{w}{h} \qquad (s_{x} \ne s_{y})
    If you must crop in the document, put the trim values in a comment naming the file they were measured against; a new export rarely needs the same numbers.

    Raster or vector, decided per figure

    The rule that makes a document look typeset rather than assembled: anything made of lines and text is a vector (a PDF export, or drawn with TikZ/pgfplots); anything with photographic detail is a raster (PNG for screenshots, JPEG for photographs, and only at the quality the camera gave you). A vector figure scales without loss and its labels can be set in the same font and size as your prose; a raster figure reveals its resolution the moment it is enlarged and its text is always a different size from the document's.

    The subtle trap is scaling a raster down. Resampling 1200 px into a 40 mm box throws away detail, can produce moiré on fine hatching, and some PDF writers then re-encode it at a lower effective resolution still. Scaling up is obviously worse. Set the export size so that the natural size is close to the size you print at, and never let a screenshot be re-saved by a viewer or a chat application: each round trip re-encodes it.

    Screenshots taken on a HiDPI screen are the one case where "place it at 50%" is correct practice: capture at 2x and write width=0.5\textwidth, which lands you at a crisp 200 ppi or better on paper. Give the box a border so it does not float in white space — \fbox{...}, or the max width key of adjustbox as in the listing below.

    Whole multi-page PDFs belong to a different tool: pdfpages inserts pages or page groups with \includepdf[pages=-,nup=2x1]{manual.pdf}, and it is a proper document-level package rather than something to squeeze through \includegraphics. Only one page of a multi-page PDF can be included as a graphic, via page=⟨n⟩; pdflatex has no notion of a multi-page figure.

    \documentclass[a4paper]{article}
    \usepackage{graphicx}
    \usepackage{adjustbox}
    \begin{document}
    
    % Screenshots: capture at 2x, place at half width, never re-save.
    \begin{figure}[htbp]
      \centering
      \begin{adjustbox}{max width=0.9\textwidth,center}
        \includegraphics{screenshot-hidpi}   % 2400 px wide -> about 150 ppi here
      \end{adjustbox}
      \caption{The dialog, placed at half its capture resolution.}
      \label{fig:shot}
    \end{figure}
    
    % Plots: export PDF from the producing program, with a tight bbox.
    %   MATLAB   print -dpdf -r600 fig.pdf
    %   Python   fig.savefig('fig.pdf', bbox_inches='tight', pad_inches=0.02)
    %   Inkscape File -> Export -> PDF (crop region: drawing), then commit it.
    \begin{figure}[htbp]
      \centering
      \includegraphics[width=0.68\textwidth]{decay-curve}
      \caption{Exponential decay. Because this is a vector PDF, the axis labels
                are drawn in the document font and survive any zoom.}
      \label{fig:decay}
    \end{figure}
    
    \end{document}

    When it does not work

    LaTeX Error: File 'fig1.pdf' not found. Three candidates: the file is not on the search path (check the trailing slash and the letter case), the extension list does not contain the file you actually have, or the engine cannot read that format at all — an .eps under pdflatex reports exactly this error. Separate them by moving the file next to the main .tex and including it by bare name; if that works, your path or your extension list was wrong.

    Cannot determine size of graphic and the bb-related complaints mean the file has no usable size: an EPS without a %%BoundingBox, a truncated or freshly-moved PDF, or a format the driver does not know. Run extractbb figure.pdf for the PDF case, regenerate or convert the EPS, or state the size yourself with natwidth= and natheight= so graphicx stops asking.

    PDF inclusion: found PDF version ..., but at most version ... supported is fixed by \pdfminorversion=7 in the preamble. Missing \endcsname inserted while loading a graphic is nearly always a stray & or a space in the directory name, and You cannot submit this batch file to pdfTeX (or the equivalent MiKTeX prompt) means an automatic conversion such as epstopdf or the svg package tried to run a program and was refused: enable --shell-escape for that build, or convert once by hand and commit the result.

    A figure that is present in the PDF but invisible on the page was usually included in horizontal mode and then broken by a following paragraph, or was cropped to nothing by its own trim values. Put \centering first inside the float and halve the trim numbers to test. And if only some figures update after you edit them, that is the lazy loading from the first section: the file is read at ship-out time, so compile again, and check whether the viewer is caching by file name rather than by content.

    w_{\mathrm{vis}} = w_{\mathrm{bb}} - l_{\mathrm{trim}} - r_{\mathrm{trim}}
    w_{\mathrm{vis}} = w_{\mathrm{bb}} - l_{\mathrm{trim}} - r_{\mathrm{trim}}
    Debugging order that works: bare file name next to the main source, then draft to see the box, then the extension list, then the engine-and-format table.

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    d_{\mathrm{eff}} = \frac{n_{\mathrm{px}}}{w_{\mathrm{print}}/25.4} = \frac{1200}{38/25.4} \approx 802\,\mathrm{ppi}
    \documentclass[a4paper]{article}
    \frac{w^{\prime}}{w} = \frac{h^{\prime}}{h} \quad\Longleftrightarrow\quad \text{exactly one of } w^{\prime},\,h^{\prime}
    \frac{w^{\prime}}{h^{\prime}} = \frac{s_{x}\,w}{s_{y}\,h} \ne \frac{w}{h} \qquad (s_{x} \ne s_{y})
    w_{\mathrm{vis}} = w_{\mathrm{bb}} - l_{\mathrm{trim}} - r_{\mathrm{trim}}

    Common mistakes

    • Omitting the trailing slash in \graphicspath{{figures}{plots}}. The lookup then concatenates figuresmyplot.pdf and reports a missing file that is plainly on disk.
    • Setting both width= and height= without keepaspectratio: circles become ellipses and every label inside the plot inherits the distortion.
    • Sizing a figure against \textwidth while it sits inside a minipage or a sub-figure. Inside a box, use \linewidth, which is that box's width.
    • Keeping .eps or .svg sources and expecting pdflatex to cope. Convert to PDF once and commit the PDF, or accept a permanent --shell-escape dependency in the build.
    • A file name whose case differs from the argument (Fig1.pdf versus \includegraphics{fig1}): compiles on Windows, fails on a Linux server.
    • Re-saving screenshots through a viewer or a chat app. Every round trip re-encodes the image, discards the declared resolution and makes the natural size jump.
    • Rotating with angle=90 and then sizing with height=: the rotated box is measured by totalheight, so the figure overflows the text block.

    Questions about this lesson

    Can I use a PNG image in LaTeX?
    Yes. PNG is one of the three formats pdflatex, lualatex and xelatex accept directly, alongside PDF and JPEG. Put the file on the search path and give a width: includegraphics[width=0.6\linewidth]{plot.png}. PNG is right for screenshots; for plots produced by software, a vector PDF keeps the labels crisp.
    Why does LaTeX say file not found when the file is there?
    Four usual causes: a graphicspath entry without its trailing slash, a letter-case difference between the file name and the argument, an extension the engine cannot read (EPS or SVG under pdflatex), or a space in the directory name. Test by moving the file next to the main .tex and including it by bare name.
    How do I make an image exactly as wide as the text?
    Give a relative width inside the box you are filling: width=\linewidth in ordinary text or in a minipage, width=\columnwidth in a two-column document. Avoid absolute units such as in or cm, because they stop being correct the moment the page geometry changes.
    What is the draft option in graphicx for?
    It draws a correctly sized box with the file name in it instead of loading the image. Page breaks and spacing stay identical, nothing is decoded, and a figure-heavy document compiles in a fraction of the time. Turn it off with the final option or with \setkeys{Gin}{draft=false}.
    Which format should I export from matplotlib or Origin?
    PDF, with a tight bounding box (matplotlib: bbox_inches="tight"). The figure stays a vector, so it scales without loss and its text can match the document font. Export SVG only if you still intend to edit it, and convert that to PDF before it reaches LaTeX.
    Do I need to install a package to insert pictures?
    No. graphicx belongs to the required graphics bundle and is present in TeX Live and MiKTeX out of the box: \usepackage{graphicx} is all you need. For inserting whole PDF documents as pages, use pdfpages, which is a separate package.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.