> ## Documentation Index
> Fetch the complete documentation index at: https://resources.latex-cloud-studio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# LaTeX \includegraphics: Insert, Resize, Trim, and Crop Images

> Use \includegraphics and graphicx to insert, resize, trim, and crop images in LaTeX. Includes trim order, clip, figure captions, paths, and fixes.

export const RenderedOutput = ({title = "Rendered output", ctaHref, ctaLabel = "Open LaTeX Cloud Studio", children}) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const trackEditorCta = () => {
    const target = new URL(ctaHref, window.location.href);
    globalThis.posthog?.capture?.("docs_app_cta_clicked", {
      source_page: window.location.pathname,
      source_section: "rendered_output",
      cta_variant: "first_compiled_example",
      target_url: target.toString(),
      target_utm_source: target.searchParams.get("utm_source"),
      target_utm_medium: target.searchParams.get("utm_medium"),
      target_utm_campaign: target.searchParams.get("utm_campaign"),
      target_utm_content: target.searchParams.get("utm_content")
    }, {
      transport: "sendBeacon",
      send_instantly: true
    });
  };
  return <details className="rendered-output" onToggle={event => setIsExpanded(event.currentTarget.open)}>
      <summary className="rendered-output__summary">
        <span className="rendered-output__title">{title}</span>
        <span className="rendered-output__hint" aria-hidden="true">View compiled result</span>
      </summary>
      {isExpanded && <div className="rendered-output__content">
          {children}
          {ctaHref && <aside className="rendered-output__cta" aria-label="Continue in the LaTeX editor">
              <span>
                <strong>Ready to use this syntax?</strong>
                Continue in the browser editor when you want to adapt the example in a real project.
              </span>
              <a href={ctaHref} onClick={trackEditorCta}>{ctaLabel}<span aria-hidden="true"> →</span></a>
            </aside>}
        </div>}
    </details>;
};

export const LatexSource = ({filename, source}) => {
  const [copyStatus, setCopyStatus] = useState("Copy");
  const copySource = async () => {
    try {
      await navigator.clipboard.writeText(source);
      setCopyStatus("Copied");
    } catch {
      setCopyStatus("Select and copy");
    }
  };
  return <figure className="latex-source">
      <figcaption className="latex-source__header">
        <span className="latex-source__filename">{filename}</span>
        <button type="button" className="latex-source__copy" onClick={copySource} aria-live="polite">
          {copyStatus}
        </button>
      </figcaption>
      <pre className="latex-source__pre" aria-label={`LaTeX source: ${filename}`} tabIndex="0">
        <code className="language-latex">{source}</code>
      </pre>
    </figure>;
};

export const LatexPreview = ({src, alt, caption, width, height}) => {
  const minZoom = 1;
  const maxZoom = 3;
  const zoomStep = 0.5;
  const measureSvgContent = async (assetSrc, pageWidth, pageHeight) => {
    const cacheKey = "__latexCloudSvgContentBoxCache";
    const contentBoxCache = globalThis[cacheKey] ?? new Map();
    globalThis[cacheKey] = contentBoxCache;
    if (contentBoxCache.has(assetSrc)) return contentBoxCache.get(assetSrc);
    const measurement = (async () => {
      const assetUrl = new URL(assetSrc, window.location.href);
      if (assetUrl.origin !== window.location.origin) {
        throw new Error("Rendered output must use a same-origin SVG asset.");
      }
      const response = await fetch(assetUrl, {
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error(`Rendered output request failed with ${response.status}.`);
      const source = await response.text();
      const documentNode = new DOMParser().parseFromString(source, "image/svg+xml");
      if (documentNode.querySelector("parsererror")) throw new Error("Rendered output is not valid SVG.");
      const sourceSvg = documentNode.documentElement;
      sourceSvg.querySelectorAll("script, foreignObject").forEach(node => node.remove());
      [sourceSvg, ...sourceSvg.querySelectorAll("*")].forEach(node => {
        [...node.attributes].forEach(attribute => {
          if ((/^on/i).test(attribute.name)) node.removeAttribute(attribute.name);
          if ((attribute.name === "href" || attribute.name === "xlink:href") && !attribute.value.startsWith("#")) {
            node.removeAttribute(attribute.name);
          }
        });
      });
      const measurementHost = document.createElement("div");
      measurementHost.className = "latex-preview__measurement-host";
      const measuredSvg = document.importNode(sourceSvg, true);
      measuredSvg.setAttribute("aria-hidden", "true");
      measurementHost.appendChild(measuredSvg);
      document.body.appendChild(measurementHost);
      try {
        const measuredElements = [...measuredSvg.children].filter(node => !["defs", "desc", "metadata", "style", "title"].includes(node.tagName.toLowerCase()));
        const elementBounds = measuredElements.map(node => node.getBBox()).filter(box => [box.x, box.y, box.width, box.height].every(Number.isFinite) && box.width > 0 && box.height > 0);
        if (elementBounds.length === 0) {
          throw new Error("Rendered output has no measurable visible content.");
        }
        const sortedBounds = [...elementBounds].sort((left, right) => left.y - right.y);
        const clusterGap = pageHeight * 0.045;
        const clusters = [];
        sortedBounds.forEach(box => {
          const current = clusters[clusters.length - 1];
          if (!current || box.y - current.bottom > clusterGap) {
            clusters.push({
              boxes: [box],
              bottom: box.y + box.height
            });
            return;
          }
          current.boxes.push(box);
          current.bottom = Math.max(current.bottom, box.y + box.height);
        });
        const contentClusters = clusters.filter(cluster => {
          const clusterBox = cluster.boxes.reduce((combined, box) => {
            const right = Math.max(combined.x + combined.width, box.x + box.width);
            const bottom = Math.max(combined.y + combined.height, box.y + box.height);
            const x = Math.min(combined.x, box.x);
            const y = Math.min(combined.y, box.y);
            return {
              x,
              y,
              width: right - x,
              height: bottom - y
            };
          });
          const centerY = clusterBox.y + clusterBox.height / 2;
          const isMarginFurniture = cluster.boxes.length <= 2 && clusterBox.width < pageWidth * 0.2 && clusterBox.height < pageHeight * 0.04 && (centerY < pageHeight * 0.08 || centerY > pageHeight * 0.8);
          return !isMarginFurniture;
        });
        const visibleBounds = (contentClusters.length > 0 ? contentClusters : clusters).flatMap(cluster => cluster.boxes);
        const bounds = visibleBounds.reduce((combined, box) => {
          const right = Math.max(combined.x + combined.width, box.x + box.width);
          const bottom = Math.max(combined.y + combined.height, box.y + box.height);
          const x = Math.min(combined.x, box.x);
          const y = Math.min(combined.y, box.y);
          return {
            x,
            y,
            width: right - x,
            height: bottom - y
          };
        });
        const clampValue = (value, minimum, maximum) => Math.min(maximum, Math.max(minimum, value));
        const padding = Math.max(8, Math.min(pageWidth, pageHeight) * 0.025);
        const x = clampValue(bounds.x - padding, 0, pageWidth);
        const y = clampValue(bounds.y - padding, 0, pageHeight);
        const right = clampValue(bounds.x + bounds.width + padding, 0, pageWidth);
        const bottom = clampValue(bounds.y + bounds.height + padding, 0, pageHeight);
        return {
          x,
          y,
          width: right - x,
          height: bottom - y
        };
      } finally {
        measurementHost.remove();
      }
    })();
    contentBoxCache.set(assetSrc, measurement);
    measurement.catch(() => contentBoxCache.delete(assetSrc));
    return measurement;
  };
  const renderPreviewAsset = ({contentBox: assetContentBox, loading}) => {
    if (!assetContentBox) {
      return <img className="latex-preview__asset" src={src} alt={alt} width={width} height={height} loading={loading} draggable="false" />;
    }
    return <svg className="latex-preview__asset" viewBox={`${assetContentBox.x} ${assetContentBox.y} ${assetContentBox.width} ${assetContentBox.height}`} preserveAspectRatio="xMidYMid meet" role="img" aria-label={alt}>
        <image href={src} x="0" y="0" width={width} height={height} />
      </svg>;
  };
  const [isOpen, setIsOpen] = useState(false);
  const [frameMode, setFrameMode] = useState("content");
  const [viewMode, setViewMode] = useState("fit");
  const [zoom, setZoom] = useState(minZoom);
  const [contentBox, setContentBox] = useState(null);
  const [measurementStatus, setMeasurementStatus] = useState("loading");
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const viewportRef = useRef(null);
  const previousFocusRef = useRef(null);
  const dragRef = useRef(null);
  useEffect(() => {
    let isCurrent = true;
    setMeasurementStatus("loading");
    measureSvgContent(src, width, height).then(box => {
      if (!isCurrent) return;
      setContentBox(box);
      setMeasurementStatus("ready");
    }).catch(() => {
      if (!isCurrent) return;
      setContentBox(null);
      setFrameMode("page");
      setMeasurementStatus("error");
    });
    return () => {
      isCurrent = false;
    };
  }, [height, src, width]);
  const closeViewer = useCallback(() => {
    setIsOpen(false);
  }, []);
  const openViewer = () => {
    previousFocusRef.current = document.activeElement;
    setFrameMode(contentBox ? "content" : "page");
    setViewMode("fit");
    setZoom(minZoom);
    setIsOpen(true);
  };
  const applyZoom = useCallback(nextZoom => {
    const boundedZoom = Math.min(maxZoom, Math.max(minZoom, nextZoom));
    setViewMode("custom");
    setZoom(boundedZoom);
  }, []);
  const zoomIn = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom + zoomStep : zoom + zoomStep);
  }, [applyZoom, viewMode, zoom]);
  const zoomOut = useCallback(() => {
    applyZoom(viewMode === "fit" ? minZoom : zoom - zoomStep);
  }, [applyZoom, viewMode, zoom]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();
    return () => {
      document.body.style.overflow = previousOverflow;
      previousFocusRef.current?.focus?.();
    };
  }, [isOpen]);
  useEffect(() => {
    if (!isOpen) return undefined;
    const handleKeyDown = event => {
      if (event.key === "Escape") {
        event.preventDefault();
        closeViewer();
        return;
      }
      if ((event.key === "+" || event.key === "=") && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomIn();
        return;
      }
      if (event.key === "-" && !event.metaKey && !event.ctrlKey) {
        event.preventDefault();
        zoomOut();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = [...dialogRef.current.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')];
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [closeViewer, isOpen, zoomIn, zoomOut]);
  const startDrag = event => {
    if (event.button !== 0 || !viewportRef.current) return;
    const viewport = viewportRef.current;
    dragRef.current = {
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      scrollLeft: viewport.scrollLeft,
      scrollTop: viewport.scrollTop
    };
    viewport.setPointerCapture(event.pointerId);
    viewport.dataset.dragging = "true";
  };
  const continueDrag = event => {
    const drag = dragRef.current;
    const viewport = viewportRef.current;
    if (!drag || !viewport || drag.pointerId !== event.pointerId) return;
    viewport.scrollLeft = drag.scrollLeft - (event.clientX - drag.x);
    viewport.scrollTop = drag.scrollTop - (event.clientY - drag.y);
  };
  const stopDrag = event => {
    const viewport = viewportRef.current;
    if (viewport?.hasPointerCapture(event.pointerId)) viewport.releasePointerCapture(event.pointerId);
    if (viewport) delete viewport.dataset.dragging;
    dragRef.current = null;
  };
  const activeContentBox = frameMode === "content" ? contentBox : null;
  const activeWidth = activeContentBox?.width ?? width;
  const activeHeight = activeContentBox?.height ?? height;
  const activeRatio = activeWidth / activeHeight;
  const inlineContentBox = measurementStatus === "ready" ? contentBox : null;
  const inlineWidth = inlineContentBox?.width ?? width;
  const inlineHeight = inlineContentBox?.height ?? height;
  const inlineGeometry = {
    aspectRatio: `${inlineWidth} / ${inlineHeight}`,
    maxWidth: `${30 * inlineWidth / inlineHeight}rem`
  };
  const imageStyle = viewMode === "fit" ? {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: "100%",
    maxWidth: `${Math.max(16, activeRatio * 78)}dvh`
  } : {
    aspectRatio: `${activeWidth} / ${activeHeight}`,
    width: `${zoom * 100}%`,
    maxWidth: "none"
  };
  const zoomLabel = viewMode === "fit" ? frameMode === "content" ? "Fit content" : "Full page" : `${Math.round(zoom * 100)}%`;
  return <figure className="latex-preview">
      <button type="button" className="latex-preview__trigger" onClick={openViewer} aria-haspopup="dialog" aria-label={`Open zoomable preview: ${alt}`}>
        <span className="latex-preview__page" style={inlineGeometry}>
          {measurementStatus === "loading" ? <span className="latex-preview__loading" role="status">Preparing compiled output…</span> : renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: inlineContentBox,
    loading: "lazy"
  })}
        </span>
        <span className="latex-preview__trigger-label" aria-hidden="true">
          <span className="latex-preview__trigger-icon">⌕</span>
          Open viewer
        </span>
      </button>
      <figcaption className="latex-preview__caption">
        <span>
          {caption}
          {measurementStatus === "error" && <span className="latex-preview__status" role="status"> Content fit is unavailable; the complete vector page is shown.</span>}
        </span>
        <a href={src} target="_blank" rel="noreferrer" className="latex-preview__source-link">Open SVG</a>
      </figcaption>

      {isOpen && <div className="latex-preview__backdrop" onMouseDown={event => {
    if (event.target === event.currentTarget) closeViewer();
  }}>
          <section ref={dialogRef} className="latex-preview__dialog" role="dialog" aria-modal="true" aria-label={`Rendered LaTeX viewer: ${alt}`}>
            <header className="latex-preview__toolbar">
              <div className="latex-preview__identity">
                <span className="latex-preview__eyebrow">Compiled LaTeX</span>
                <span className="latex-preview__filename">{alt}</span>
              </div>
              <div className="latex-preview__controls" aria-label="Preview controls">
                <button type="button" className={frameMode === "content" && viewMode === "fit" ? "is-active" : undefined} disabled={!contentBox} onClick={() => {
    setFrameMode("content");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Fit content
                </button>
                <button type="button" className={frameMode === "page" && viewMode === "fit" ? "is-active" : undefined} onClick={() => {
    setFrameMode("page");
    setViewMode("fit");
    setZoom(minZoom);
  }}>
                  Full page
                </button>
                <span className="latex-preview__zoom-group">
                  <button type="button" onClick={zoomOut} disabled={viewMode === "fit" || zoom <= minZoom} aria-label="Zoom out">−</button>
                  <output aria-live="polite" aria-label="Current zoom">{zoomLabel}</output>
                  <button type="button" onClick={zoomIn} disabled={viewMode !== "fit" && zoom >= maxZoom} aria-label="Zoom in">+</button>
                </span>
                <a href={src} target="_blank" rel="noreferrer">Open SVG</a>
                <button ref={closeButtonRef} type="button" className="latex-preview__close" onClick={closeViewer} aria-label="Close rendered LaTeX viewer">
                  Close
                </button>
              </div>
            </header>
            <div ref={viewportRef} className="latex-preview__viewport" data-view-mode={viewMode} onPointerDown={startDrag} onPointerMove={continueDrag} onPointerUp={stopDrag} onPointerCancel={stopDrag}>
              <span className="latex-preview__dialog-page" style={imageStyle}>
                {renderPreviewAsset({
    src,
    alt,
    width,
    height,
    contentBox: activeContentBox
  })}
              </span>
            </div>
            <footer className="latex-preview__viewer-note">
              Compiler-generated vector output · Use +/− to zoom · Drag to pan · Esc to close
            </footer>
          </section>
        </div>}
    </figure>;
};

To insert an image in LaTeX, load `graphicx` and use `\includegraphics{...}`. Add `width` or `height` to resize it, and use `trim=left bottom right top,clip` to crop unwanted margins.

<Info>
  **Quick answer**: add `\usepackage{graphicx}` to the preamble, then write `\includegraphics[width=0.8\textwidth]{image-file}`. To crop, use `\includegraphics[trim=1cm 2cm 1cm 2cm,clip]{image-file}`. The trim values are always ordered **left, bottom, right, top**.

  **Related topics**: [Figure positioning](/learn/latex/figures/positioning) | [Tabular environment](/learn/latex/tables/tabular) | [Package management](/learn/latex/package-management)
</Info>

## Common image tasks

| If you need...                 | Use                                                                   |
| ------------------------------ | --------------------------------------------------------------------- |
| Insert one image               | `\includegraphics{image}`                                             |
| Set width relative to the page | `\includegraphics[width=0.7\textwidth]{image}`                        |
| Keep the aspect ratio          | `\includegraphics[width=5cm,keepaspectratio]{image}`                  |
| Crop whitespace                | `\includegraphics[trim=1cm 0.5cm 1cm 0.5cm,clip]{image}`              |
| Add caption and label          | wrap the image in `\begin{figure}...\end{figure}`                     |
| Put two images side by side    | use two `\includegraphics` commands with widths like `0.45\textwidth` |

## Quick Start

<LatexSource filename="quick-image.tex" source={"\\documentclass{article}\n\\usepackage{graphicx}\n\n\\begin{document}\n\n\\begin{figure}[htbp]\n  \\centering\n  \\includegraphics[width=0.7\\textwidth]{example-image}\n  \\caption{Example image}\n  \\label{fig:example}\n\\end{figure}\n\n\\end{document}"} />

<RenderedOutput title="Rendered output" ctaHref="https://app.latex-cloud-studio.com/?utm_source=resources&utm_medium=rendered_output&utm_campaign=docs_open_app&utm_content=learn_latex_figures_inserting_images">
  <LatexPreview src="/images/rendered/learn-latex-figures-inserting-images-01/page-1.svg" alt="Compiled PDF page 1 from quick-image.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

## Trim and crop images with `includegraphics`

The `trim` option removes material from the four edges. Its order is **left, bottom, right, top**—not the clockwise order that many users expect. Add `clip`; without it, LaTeX changes the image's bounding box but can still draw the trimmed material.

<LatexSource filename="trim-image.tex" source={"% Remove 1 cm left/right and 2 cm bottom/top\n\\includegraphics[\n  width=0.8\\textwidth,\n  trim=1cm 2cm 1cm 2cm,\n  clip\n]{image.pdf}\n\n% Remove only 12 mm from the top\n\\includegraphics[trim=0 0 0 12mm,clip]{image.pdf}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

<Card title="Expected output" icon="crop">
  The PDF shows the cropped image at 80% of the text width. The first example removes material from all four sides; the second removes only the top 12 mm.
</Card>

LaTeX applies `width` to the cropped result. Use units such as `cm`, `mm`, `pt`, or `bp`; four bare numbers are interpreted differently depending on the graphics driver and are easier to misread.

<Warning>
  If `trim` appears to do nothing, check for a missing `clip` option first. If the wrong edge disappears, verify that the values follow `left bottom right top`.
</Warning>

## Basic Image Insertion

### Simple Image Include

<LatexSource filename="basic-image.tex" source={"\\documentclass{article}\n\\usepackage{graphicx}\n\\begin{document}\n\n% Basic image insertion\n\\includegraphics{example-image}\n\n% With file extension\n\\includegraphics{photo.jpg}\n\n% From subfolder\n\\includegraphics{images/diagram.png}\n\n% With full path (use forward slashes)\n\\includegraphics{/Users/name/pictures/graph.pdf}\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Supported Image Formats

| Compiler        | Formats Supported         |
| --------------- | ------------------------- |
| **pdfLaTeX**    | PDF, PNG, JPG/JPEG        |
| **XeLaTeX**     | PDF, PNG, JPG/JPEG, EPS\* |
| **LuaLaTeX**    | PDF, PNG, JPG/JPEG, EPS\* |
| **LaTeX (DVI)** | EPS, PS                   |

\*EPS requires additional configuration

<Tip>
  **Best practices for formats:**

  * **PDF**: Vector graphics, diagrams, plots
  * **PNG**: Screenshots, images with transparency
  * **JPG**: Photographs, images without transparency
</Tip>

## Scaling Images

### Width and Height Control

<LatexSource filename="scaling-images.tex" source={"\\documentclass{article}\n\\usepackage{graphicx}\n\\begin{document}\n\n% Scale by width\n\\includegraphics[width=5cm]{image}\n\\includegraphics[width=0.8\\textwidth]{image}\n\\includegraphics[width=\\columnwidth]{image}\n\n% Scale by height\n\\includegraphics[height=3cm]{image}\n\\includegraphics[height=0.25\\textheight]{image}\n\n% Scale by both (may distort)\n\\includegraphics[width=5cm,height=3cm]{image}\n\n% Keep aspect ratio with one dimension\n\\includegraphics[width=5cm,keepaspectratio]{image}\n\n% Scale factor\n\\includegraphics[scale=0.5]{image}  % 50% of original\n\\includegraphics[scale=1.2]{image}  % 120% of original\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Common Width References

<LatexSource filename="width-references.tex" source={"% Page dimensions\n\\includegraphics[width=\\textwidth]{image}      % Full text width\n\\includegraphics[width=\\columnwidth]{image}    % Column width\n\\includegraphics[width=\\linewidth]{image}      % Current line width\n\\includegraphics[width=\\paperwidth]{image}     % Full paper width\n\n% Relative sizes\n\\includegraphics[width=0.5\\textwidth]{image}   % Half text width\n\\includegraphics[width=0.33\\columnwidth]{image} % Third of column\n\n% Using calc package\n\\usepackage{calc}\n\\includegraphics[width=\\textwidth-2cm]{image}  % Text width minus 2cm"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Figure Environment

### Basic Figure

<LatexSource filename="figure-environment.tex" source={"\\documentclass{article}\n\\usepackage{graphicx}\n\\begin{document}\n\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=0.6\\textwidth]{example-image}\n  \\caption{A sample figure with caption}\n  \\label{fig:sample}\n\\end{figure}\n\nAs shown in Figure \\ref{fig:sample}, the image demonstrates...\n\n% Alternative with short caption for list of figures\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=0.5\\textwidth]{graph}\n  \\caption[Short caption]{Long descriptive caption that appears below the figure}\n  \\label{fig:graph}\n\\end{figure}\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Figure Placement Options

| Option | Meaning                | Priority |
| ------ | ---------------------- | -------- |
| `h`    | Here (approximately)   | Low      |
| `t`    | Top of page            | Medium   |
| `b`    | Bottom of page         | Medium   |
| `p`    | Page of floats         | Low      |
| `H`    | HERE (exactly)\*       | Forced   |
| `!`    | Override LaTeX's rules | Modifier |

\*Requires `\usepackage{float}`

<LatexSource filename="figure-placement.tex" source={"% Preferred placement order\n\\begin{figure}[htbp]  % Try here, then top, bottom, finally float page\n\n% Force placement\n\\usepackage{float}\n\\begin{figure}[H]  % Place exactly here\n\n% Override LaTeX's aesthetic rules\n\\begin{figure}[!h]  % Try harder to place here"} />

<RenderedOutput title="Expected effect">
  <Info>
    This code is a contextual or intentionally partial LaTeX excerpt, not a self-contained compilable document. Its visible result depends on the surrounding document, so the documentation shows the expected role without inventing a standalone preview.
  </Info>
</RenderedOutput>

## Multiple Images

### Side by Side Images

<LatexSource filename="side-by-side.tex" source={"\\documentclass{article}\n\\usepackage{graphicx}\n\\begin{document}\n\n% Method 1: Simple side by side\n\\begin{figure}[h]\n  \\centering\n  \\includegraphics[width=0.45\\textwidth]{image1}\n  \\hfill\n  \\includegraphics[width=0.45\\textwidth]{image2}\n  \\caption{Two images side by side}\n\\end{figure}\n\n% Method 2: With individual captions (subcaption package)\n\\usepackage{subcaption}\n\\begin{figure}[h]\n  \\centering\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{image1}\n    \\caption{First subcaption}\n    \\label{fig:sub1}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{0.45\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{image2}\n    \\caption{Second subcaption}\n    \\label{fig:sub2}\n  \\end{subfigure}\n  \\caption{Main figure caption}\n  \\label{fig:main}\n\\end{figure}\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Grid of Images

<LatexSource filename="image-grid.tex" source={"\\usepackage{subcaption}\n\n\\begin{figure}[h]\n  \\centering\n  % First row\n  \\begin{subfigure}[b]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img1}\n    \\caption{Image 1}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img2}\n    \\caption{Image 2}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img3}\n    \\caption{Image 3}\n  \\end{subfigure}\n\n  % Second row\n  \\begin{subfigure}[b]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img4}\n    \\caption{Image 4}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img5}\n    \\caption{Image 5}\n  \\end{subfigure}\n  \\hfill\n  \\begin{subfigure}[b]{0.3\\textwidth}\n    \\centering\n    \\includegraphics[width=\\textwidth]{img6}\n    \\caption{Image 6}\n  \\end{subfigure}\n\n  \\caption{Grid of six images}\n\\end{figure}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Image Transformations

### Rotation and Flipping

<LatexSource filename="transformations.tex" source={"\\documentclass{article}\n\\usepackage{graphicx}\n\\begin{document}\n\n% Rotate image\n\\includegraphics[angle=90]{image}              % 90 degrees\n\\includegraphics[angle=-45]{image}             % -45 degrees\n\\includegraphics[angle=180]{image}             % Upside down\n\n% Rotate and scale\n\\includegraphics[angle=45,width=5cm]{image}\n\n% Origin of rotation\n\\includegraphics[angle=90,origin=c]{image}     % Center (default)\n\\includegraphics[angle=90,origin=tl]{image}    % Top left\n\\includegraphics[angle=90,origin=br]{image}    % Bottom right\n\n% Reflection (negative scaling)\n\\includegraphics[width=5cm]{image}             % Normal\n\\includegraphics[width=-5cm]{image}            % Horizontal flip\n\\includegraphics[width=5cm,height=-3cm]{image} % Vertical flip\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Advanced Techniques

### Wrapping Text Around Images

<LatexSource filename="wrap-text.tex" source={"\\documentclass{article}\n\\usepackage{graphicx}\n\\usepackage{wrapfig}\n\\begin{document}\n\n\\begin{wrapfigure}{r}{0.4\\textwidth}\n  \\centering\n  \\includegraphics[width=0.38\\textwidth]{image}\n  \\caption{A wrapped figure}\n\\end{wrapfigure}\n\nThis text wraps around the figure. The figure is positioned on the\nright side of the page, and the text flows around it naturally.\nThis is useful for smaller images that don't need the full width\nof the page. Continue with more text to see the wrapping effect...\n\n% Options: r (right), l (left), i (inner), o (outer)\n\\begin{wrapfigure}{l}{0.3\\textwidth}\n  \\vspace{-20pt}  % Adjust vertical position\n  \\centering\n  \\includegraphics[width=0.28\\textwidth]{small-image}\n  \\vspace{-20pt}\n  \\caption{Left aligned}\n  \\vspace{-10pt}\n\\end{wrapfigure}\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Image Paths

<LatexSource filename="image-paths.tex" source={"% Set graphics path\n\\graphicspath{{images/}{figures/}{../pics/}}\n\n% Now you can use just the filename\n\\includegraphics{photo}  % Searches in all specified paths\n\n% Multiple paths with subdirectories\n\\graphicspath{\n  {./images/}\n  {./figures/photos/}\n  {./figures/diagrams/}\n  {../common/images/}\n}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

### Draft Mode

<LatexSource filename="draft-mode.tex" source={"% Show boxes instead of images (faster compilation)\n\\usepackage[draft]{graphicx}\n\n% Or document-wide\n\\documentclass[draft]{article}\n\n% Override draft mode for specific image\n\\includegraphics[draft=false,width=5cm]{important-image}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Image Formats and Conversion

### Working with Different Formats

<LatexSource filename="format-handling.tex" source={"% Let LaTeX determine format\n\\DeclareGraphicsExtensions{.pdf,.png,.jpg,.jpeg}\n\\includegraphics{image}  % Finds image.pdf, image.png, etc.\n\n% Force specific format\n\\includegraphics[ext=.png]{image}\n\n% EPS to PDF conversion (pdfLaTeX)\n\\usepackage{epstopdf}\n\\includegraphics{diagram.eps}  % Automatically converted"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

## Best Practices

<Tip>
  **Image guidelines:**

  1. **Resolution**: Use 300 DPI for print, 96-150 DPI for screen
  2. **File size**: Optimize images before including them
  3. **Formats**: Use vector (PDF) for diagrams, raster (PNG/JPG) for photos
  4. **Naming**: Avoid spaces and special characters in filenames
  5. **Organization**: Keep images in a dedicated folder
  6. **Captions**: Always include descriptive captions
  7. **References**: Label all figures for cross-referencing
</Tip>

## Troubleshooting

| Problem                                       | Likely cause                                   | Fix                                                                                                   |
| --------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `Undefined control sequence \includegraphics` | `graphicx` is not loaded                       | Add `\usepackage{graphicx}` to the preamble                                                           |
| `File ... not found`                          | Wrong path, extension, or filename case        | Check the uploaded filename and use forward slashes in paths                                          |
| `trim` does not visibly crop                  | `clip` is missing                              | Add `clip` after the four trim values                                                                 |
| The wrong edge is cropped                     | Trim values are in the wrong order             | Reorder them as left, bottom, right, top                                                              |
| Image looks stretched                         | Both width and height force a new aspect ratio | Set only one dimension, or add `keepaspectratio`                                                      |
| Image extends beyond the margins              | Fixed size is wider than the current text area | Start with `width=\linewidth` or a smaller fraction                                                   |
| Figure moves to another page                  | A `figure` is a float                          | Use `[htbp]` and let LaTeX place it, or review [figure positioning](/learn/latex/figures/positioning) |

For path-specific compiler messages, see [image and path errors](/learn/latex/troubleshooting/image-and-path-errors).

## Quick Reference

### Essential Commands

| Command              | Purpose       | Example                 |
| -------------------- | ------------- | ----------------------- |
| `\includegraphics{}` | Insert image  | `\includegraphics{pic}` |
| `width=`             | Set width     | `width=5cm`             |
| `height=`            | Set height    | `height=3cm`            |
| `scale=`             | Scale factor  | `scale=0.5`             |
| `angle=`             | Rotate        | `angle=90`              |
| `trim=` with `clip`  | Crop edges    | `trim=1cm 0 1cm 0,clip` |
| `\caption{}`         | Add caption   | `\caption{Description}` |
| `\label{}`           | Add reference | `\label{fig:name}`      |

### Figure Template

<LatexSource filename="example.tex" source={"\\begin{figure}[htbp]\n  \\centering\n  \\includegraphics[width=0.8\\textwidth]{filename}\n  \\caption{Descriptive caption}\n  \\label{fig:reference-name}\n\\end{figure}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt depends on project files such as images, bibliography data, or included TeX sources that are not part of this standalone code box. Its exact output is project-specific, so no fabricated preview is shown.
  </Info>
</RenderedOutput>

***

<Info>
  **Next**: Master [Figure positioning](/learn/latex/figures/positioning) to control exactly where your images appear, or learn about [Creating tables](/learn/latex/tables/creating-tables) for structured data presentation.
</Info>
