> ## 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.

# Working with Images in LaTeX

> Include, position, and format images in LaTeX. Learn graphics, subfigures, wrapping text, and advanced layout techniques.

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>;
};

Master the art of including and formatting images in LaTeX documents. This comprehensive guide covers everything from basic image inclusion to advanced layouts, optimization, and professional formatting techniques.

<Info>
  **Prerequisites**: Basic LaTeX knowledge and the graphicx package\
  **Time to complete**: 25-30 minutes\
  **Difficulty**: Intermediate\
  **What you'll learn**: Image formats, positioning, sizing, captions, subfigures, wrapping text, and advanced techniques
</Info>

## Understanding Image Basics

### Supported Image Formats

LaTeX supports different image formats depending on the compiler:

<Tabs>
  <Tab title="pdfLaTeX">
    **Supported formats**:

    * **PDF** - Vector graphics, best quality
    * **PNG** - Lossless compression, good for diagrams
    * **JPG/JPEG** - Lossy compression, good for photos
    * **EPS** - With epstopdf package

    <LatexSource filename="example.tex" source={"\\usepackage{graphicx}\n\\usepackage{epstopdf} % For EPS support"} />

    <RenderedOutput title="Expected effect">
      <Info>
        This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
      </Info>
    </RenderedOutput>
  </Tab>

  <Tab title="XeLaTeX/LuaLaTeX">
    **Supported formats**:

    * All pdfLaTeX formats
    * **SVG** - With svg package
    * **Additional formats** via system tools

    <LatexSource filename="example.tex" source={"\\usepackage{graphicx}\n\\usepackage{svg} % For SVG support"} />

    <RenderedOutput title="Expected effect">
      <Info>
        This is setup or structural LaTeX code. It changes available commands or document behavior, but it does not produce meaningful standalone page content by itself.
      </Info>
    </RenderedOutput>
  </Tab>

  <Tab title="Traditional LaTeX">
    **Supported formats**:

    * **EPS** - Encapsulated PostScript
    * **PS** - PostScript

    <LatexSource filename="example.tex" source={"\\usepackage{graphicx}\n\\DeclareGraphicsExtensions{.eps,.ps}"} />

    <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>
  </Tab>
</Tabs>

### Basic Image Inclusion

<LatexSource filename="simple-image.tex" source={"\\documentclass{article}\n\\usepackage{graphicx}\n\n\\begin{document}\n\n% Basic image inclusion\n\\includegraphics{example-image}\n\n% With explicit width\n\\includegraphics[width=5cm]{example-image}\n\n% With relative width\n\\includegraphics[width=0.8\\textwidth]{example-image}\n\n% With height specification\n\\includegraphics[height=3cm]{example-image}\n\n% Maintaining aspect ratio\n\\includegraphics[width=5cm, keepaspectratio]{example-image}\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_how_to_working_with_images">
  <LatexPreview src="/images/rendered/learn-latex-how-to-working-with-images-04/page-1.svg" alt="Compiled PDF page 1 from simple-image.tex" caption="Page 1 of 2. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />

  <LatexPreview src="/images/rendered/learn-latex-how-to-working-with-images-04/page-2.svg" alt="Compiled PDF page 2 from simple-image.tex" caption="Page 2 of 2. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={612} height={792} />
</RenderedOutput>

<LatexSource filename="image-paths.tex" source={"% Set graphics path\n\\graphicspath{{images/}{figures/}{../photos/}}\n\n% Now LaTeX searches in these directories\n\\includegraphics{myimage} % Searches all paths"} />

<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 Environments

### Basic Figures with Captions

<LatexSource filename="figure-basics.tex" source={"\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=0.8\\textwidth]{example-image}\n    \\caption{A descriptive caption for the image}\n    \\label{fig:example}\n\\end{figure}\n\n% Reference the figure\nAs shown in Figure~\\ref{fig:example}, the results are clear.\n\n% Short caption for list of figures\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth]{data-plot}\n    \\caption[Short caption]{Long descriptive caption with detailed explanation}\n    \\label{fig:data}\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>

<LatexSource filename="figure-positioning.tex" source={"% Positioning options\n% h - here (approximately)\n% t - top of page\n% b - bottom of page\n% p - separate page for floats\n% ! - override LaTeX's internal parameters\n% H - exactly here (requires float package)\n\n\\usepackage{float}\n\n\\begin{figure}[H] % Exactly here\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{diagram}\n    \\caption{This figure appears exactly here}\n\\end{figure}\n\n% Multiple positioning preferences\n\\begin{figure}[!htb] % Try here, then top, then bottom, override parameters\n    \\centering\n    \\includegraphics[width=0.7\\textwidth]{chart}\n    \\caption{Flexible positioning}\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>

### Advanced Caption Formatting

<LatexSource filename="caption-formatting.tex" source={"\\usepackage{caption}\n\\usepackage{subcaption}\n\n% Global caption setup\n\\captionsetup{\n    font=small,\n    labelfont=bf,\n    format=plain,\n    justification=centering,\n    skip=10pt\n}\n\n% Per-figure caption style\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth]{photo}\n    \\captionsetup{font=footnotesize, labelfont=sc}\n    \\caption{A photo with custom caption style}\n\\end{figure}\n\n% Caption without label\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=0.5\\textwidth]{art}\n    \\caption*{An artistic image without Figure label}\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>

## Multiple Images

### Side-by-Side Images

<LatexSource filename="side-by-side.tex" source={"% Method 1: Using minipage\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{minipage}{0.45\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{image1}\n        \\caption{First image}\n        \\label{fig:first}\n    \\end{minipage}\n    \\hfill\n    \\begin{minipage}{0.45\\textwidth}\n        \\centering\n        \\includegraphics[width=\\textwidth]{image2}\n        \\caption{Second image}\n        \\label{fig:second}\n    \\end{minipage}\n\\end{figure}\n\n% Method 2: Using subfigure (deprecated, use subcaption)\n\\usepackage{subcaption}\n\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{before}\n        \\caption{Before treatment}\n        \\label{fig:before}\n    \\end{subfigure}\n    \\hfill\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{after}\n        \\caption{After treatment}\n        \\label{fig:after}\n    \\end{subfigure}\n    \\caption{Comparison of results}\n    \\label{fig:comparison}\n\\end{figure}\n\n% Reference subfigures\nFigure~\\ref{fig:before} shows the initial state, while\nFigure~\\ref{fig:after} demonstrates the improvement.\nThe overall comparison is shown in Figure~\\ref{fig:comparison}."} />

<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 Layouts

<LatexSource filename="image-grid.tex" source={"\\begin{figure}[htbp]\n    \\centering\n    \\begin{subfigure}{0.3\\textwidth}\n        \\includegraphics[width=\\textwidth]{img1}\n        \\caption{Sample A}\n    \\end{subfigure}\n    \\hfill\n    \\begin{subfigure}{0.3\\textwidth}\n        \\includegraphics[width=\\textwidth]{img2}\n        \\caption{Sample B}\n    \\end{subfigure}\n    \\hfill\n    \\begin{subfigure}{0.3\\textwidth}\n        \\includegraphics[width=\\textwidth]{img3}\n        \\caption{Sample C}\n    \\end{subfigure}\n\n    \\vspace{0.5cm}\n\n    \\begin{subfigure}{0.3\\textwidth}\n        \\includegraphics[width=\\textwidth]{img4}\n        \\caption{Sample D}\n    \\end{subfigure}\n    \\hfill\n    \\begin{subfigure}{0.3\\textwidth}\n        \\includegraphics[width=\\textwidth]{img5}\n        \\caption{Sample E}\n    \\end{subfigure}\n    \\hfill\n    \\begin{subfigure}{0.3\\textwidth}\n        \\includegraphics[width=\\textwidth]{img6}\n        \\caption{Sample F}\n    \\end{subfigure}\n    \\caption{Grid of experimental samples}\n    \\label{fig:grid}\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>

## Text Wrapping

### Wrapping Text Around Images

<LatexSource filename="wrapfigure.tex" source={"\\usepackage{wrapfig}\n\\usepackage{lipsum} % For dummy text\n\n\\begin{document}\n\n\\section{Text Wrapping Examples}\n\n% Right-aligned wrapped figure\n\\begin{wrapfigure}{r}{0.4\\textwidth}\n    \\centering\n    \\includegraphics[width=0.35\\textwidth]{portrait}\n    \\caption{A wrapped figure}\n\\end{wrapfigure}\n\\lipsum[1-2] % Dummy text that wraps around the figure\n\n% Left-aligned wrapped figure\n\\begin{wrapfigure}{l}{0.3\\textwidth}\n    \\vspace{-20pt} % Adjust vertical position\n    \\centering\n    \\includegraphics[width=0.25\\textwidth]{icon}\n    \\caption{Left-aligned image}\n    \\vspace{-20pt} % Reduce space after\n\\end{wrapfigure}\n\\lipsum[3]\n\n% Inner/outer alignment for two-sided documents\n\\begin{wrapfigure}{o}{0.35\\textwidth} % o = outer margin\n    \\centering\n    \\includegraphics[width=0.3\\textwidth]{diagram}\n    \\caption{Outer margin placement}\n\\end{wrapfigure}\n\\lipsum[4]\n\n\\end{document}"} />

<RenderedOutput title="Expected effect">
  <Info>
    This excerpt is structurally incomplete and cannot be compiled honestly as a standalone document. It shows document-boundary syntax rather than a visible page result.
  </Info>
</RenderedOutput>

<LatexSource filename="advanced-wrapping.tex" source={"% Precise control over wrapping\n\\begin{wrapfigure}[12]{r}[0pt]{0.5\\textwidth}\n% [12] = number of narrow lines\n% {r} = placement (right)\n% [0pt] = overhang into margin\n% {0.5\\textwidth} = width\n\n    \\centering\n    \\includegraphics[width=0.45\\textwidth]{photo}\n    \\caption{Precisely positioned wrapped figure}\n\\end{wrapfigure}\n\n% Handle wrapping issues\n\\usepackage{wrapfig}\n\\setlength{\\intextsep}{10pt} % Space above and below\n\\setlength{\\columnsep}{15pt} % Space beside 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

### Scaling and Rotating

<LatexSource filename="transformations.tex" source={"\\usepackage{graphicx}\n\n% Scaling options\n\\includegraphics[scale=0.5]{image} % 50% of original\n\\includegraphics[scale=1.2]{image} % 120% of original\n\n% Rotation\n\\includegraphics[angle=90]{image} % 90 degrees counterclockwise\n\\includegraphics[angle=-45]{image} % 45 degrees clockwise\n\n% Combined transformations\n\\includegraphics[width=5cm, angle=30]{image}\n\n% Reflection\n\\reflectbox{\\includegraphics[width=3cm]{image}}\n\n% Scale to specific dimensions\n\\resizebox{5cm}{3cm}{%\n    \\includegraphics{image}%\n}\n\n% Scale proportionally\n\\resizebox{5cm}{!}{% ! maintains aspect ratio\n    \\includegraphics{image}%\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>

<LatexSource filename="clipping-trimming.tex" source={"% Trim image edges\n% trim = left bottom right top\n\\includegraphics[trim=1cm 2cm 1cm 2cm, clip, width=5cm]{image}\n\n% Viewport - select region\n\\includegraphics[viewport=20 20 200 200, clip, width=5cm]{image}\n\n% Extract part of image\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[\n        trim=50 100 50 150, % Remove edges\n        clip,\n        width=0.6\\textwidth\n    ]{full-image}\n    \\caption{Cropped section of the original image}\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>

### Special Effects

<LatexSource filename="image-effects.tex" source={"\\usepackage{graphicx}\n\\usepackage[pdftex]{transparent}\n\n% Transparency (requires pdflatex)\n\\begin{figure}[htbp]\n    \\centering\n    \\transparent{0.5}\\includegraphics[width=0.5\\textwidth]{watermark}\n    \\caption{Semi-transparent image}\n\\end{figure}\n\n% Framed images\n\\usepackage{fancybox}\n\n\\begin{figure}[htbp]\n    \\centering\n    \\shadowbox{\\includegraphics[width=0.4\\textwidth]{photo}}\n    \\caption{Image with shadow box}\n\\end{figure}\n\n\\begin{figure}[htbp]\n    \\centering\n    \\ovalbox{\\includegraphics[width=0.4\\textwidth]{portrait}}\n    \\caption{Image with oval frame}\n\\end{figure}\n\n% Custom frames\n\\setlength{\\fboxsep}{10pt}\n\\setlength{\\fboxrule}{2pt}\n\\fbox{\\includegraphics[width=0.3\\textwidth]{art}}"} />

<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

### Dynamic Image Paths

<LatexSource filename="dynamic-paths.tex" source={"% Conditional image inclusion\n\\newif\\ifprintversion\n\\printversiontrue % or \\printversionfalse\n\n\\begin{figure}[htbp]\n    \\centering\n    \\ifprintversion\n        \\includegraphics[width=0.8\\textwidth]{high-res-image}\n    \\else\n        \\includegraphics[width=0.8\\textwidth]{web-image}\n    \\fi\n    \\caption{Resolution-appropriate image}\n\\end{figure}\n\n% Multiple format search\n\\DeclareGraphicsExtensions{.pdf,.png,.jpg}\n\\includegraphics{myimage} % Searches for myimage.pdf, then .png, then .jpg\n\n% Platform-specific paths\n\\usepackage{iftex}\n\\ifXeTeX\n    \\graphicspath{{xelatex-images/}}\n\\else\n    \\graphicspath{{pdflatex-images/}}\n\\fi"} />

<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>

<LatexSource filename="draft-mode.tex" source={"% Draft mode with placeholders\n\\documentclass[draft]{article}\n\\usepackage{graphicx}\n\n% In draft mode, images show as frames with filename\n\\includegraphics[width=0.5\\textwidth]{large-image}\n\n% Force draft mode for specific image\n\\includegraphics[draft, width=0.5\\textwidth]{huge-image}\n\n% Override draft mode\n\\includegraphics[final, width=0.5\\textwidth]{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>

### External Graphics Tools

<LatexSource filename="external-tools.tex" source={"% Auto-convert formats\n\\usepackage{epstopdf}\n\\epstopdfsetup{update} % Only convert if source is newer\n\n% Include matplotlib plots\n\\usepackage{pgf}\n\\input{figure.pgf} % Generated by matplotlib\n\n% Include Inkscape SVG\n\\usepackage{svg}\n\\includesvg[width=0.5\\textwidth]{diagram}\n\n% TikZ external\n\\usepackage{tikz}\n\\usetikzlibrary{external}\n\\tikzexternalize[prefix=figures/]\n\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{tikzpicture}\n        % Complex TikZ drawing\n    \\end{tikzpicture}\n    \\caption{Externalized TikZ figure}\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>

## Optimizing Images

### File Size Management

<Tip>
  **Best practices for image optimization**:

  1. **Choose the right format**:
     * **PDF**: Vector graphics, diagrams, plots
     * **PNG**: Screenshots, diagrams with text
     * **JPG**: Photographs, complex images

  2. **Optimize before including**:
     ```bash theme={null}
     # Compress PDF
     gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf

     # Optimize PNG
     optipng -o7 image.png

     # Compress JPG
     jpegoptim --max=85 image.jpg
     ```

  3. **Use appropriate resolution**:
     * Print: 300 DPI
     * Screen: 72-96 DPI
     * Web: 72 DPI
</Tip>

### Performance Tips

<LatexSource filename="performance.tex" source={"% Preload frequently used images\n\\usepackage{graphicx}\n\\newsavebox{\\mylogo}\n\\savebox{\\mylogo}{\\includegraphics[width=2cm]{logo}}\n\n% Use the preloaded image multiple times\n\\usebox{\\mylogo} % Fast, no reloading\n\n% Bounding box for faster compilation\n\\includegraphics[bb=0 0 100 100, width=5cm]{complex-image}\n\n% External bounding box files\n% Create image.bb file with: %%BoundingBox: 0 0 595 842\n\\includegraphics[width=\\textwidth]{image} % Reads image.bb"} />

<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>

## Troubleshooting

### Common Issues and Solutions

<Warning>
  **Common image problems**:

  1. **"File not found" errors**:
     ```latex theme={null}
     % Check file extension
     \includegraphics{image.png} % Wrong
     \includegraphics{image} % Correct

     % Check path
     \graphicspath{{./images/}{../figures/}}
     ```

  2. **Wrong image size**:
     ```latex theme={null}
     % Don't use both width and height unless needed
     \includegraphics[width=5cm, height=3cm]{image} % May distort
     \includegraphics[width=5cm]{image} % Maintains ratio
     ```

  3. **Figure placement issues**:
     ```latex theme={null}
     % Too strict placement
     \begin{figure}[h] % May cause bad spacing
     \begin{figure}[htbp] % More flexible
     ```

  4. **Overflow into margins**:
     ```latex theme={null}
     % Image too wide
     \includegraphics[width=\textwidth]{image}
     % Better: leave some margin
     \includegraphics[width=0.95\textwidth]{image}
     ```
</Warning>

### Debug Mode

<LatexSource filename="debug-images.tex" source={"% Show frame around images\n\\usepackage[draft]{graphicx}\n\n% Show figure boundaries\n\\usepackage{showframe}\n\n% Track float placement\n\\usepackage{float}\n\\floatplacement{figure}{H}\n\n% List all figures\n\\listoffigures"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-working-with-images-20/page-1.svg" alt="Compiled PDF page 1 from debug-images.tex" caption="Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment. The visible fragment is compiled inside the documented minimal article wrapper." width={612} height={792} />
</RenderedOutput>

## Best Practices Checklist

<Tip>
  ✅ **Image workflow checklist**:

  * [ ] Choose appropriate file format
  * [ ] Optimize file size before inclusion
  * [ ] Use relative widths (`\textwidth`)
  * [ ] Always include captions
  * [ ] Add meaningful labels
  * [ ] Test different positions
  * [ ] Check output at final resolution
  * [ ] Verify all images are included in repository
  * [ ] Use consistent naming convention
  * [ ] Document image sources
</Tip>

## Complete Example

<LatexSource filename="complete-image-document.tex" source={"\\documentclass[11pt, a4paper]{article}\n\\usepackage{graphicx}\n\\usepackage{subcaption}\n\\usepackage{wrapfig}\n\\usepackage{float}\n\\usepackage{caption}\n\n% Setup\n\\graphicspath{{images/}{figures/}}\n\\captionsetup{font=small, labelfont=bf}\n\n\\begin{document}\n\n\\title{Comprehensive Image Examples}\n\\author{Your Name}\n\\date{\\today}\n\\maketitle\n\n\\section{Introduction}\n\nThis document demonstrates various image inclusion techniques in LaTeX.\n\n\\section{Basic Figure}\n\n\\begin{figure}[htbp]\n    \\centering\n    \\includegraphics[width=0.6\\textwidth]{example-image-a}\n    \\caption{A simple centered figure}\n    \\label{fig:simple}\n\\end{figure}\n\nAs shown in Figure~\\ref{fig:simple}, basic image inclusion is straightforward.\n\n\\section{Wrapped Figure}\n\n\\begin{wrapfigure}{r}{0.4\\textwidth}\n    \\centering\n    \\includegraphics[width=0.35\\textwidth]{example-image-b}\n    \\caption{Wrapped figure}\n    \\label{fig:wrapped}\n\\end{wrapfigure}\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris. The wrapped figure appears to the right of this text, demonstrating how text flows around images.\n\n\\section{Multiple Images}\n\n\\begin{figure}[htbp]\n    \\centering\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{example-image-a}\n        \\caption{First subfigure}\n        \\label{fig:sub1}\n    \\end{subfigure}\n    \\hfill\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{example-image-b}\n        \\caption{Second subfigure}\n        \\label{fig:sub2}\n    \\end{subfigure}\n\n    \\vspace{0.5cm}\n\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{example-image-c}\n        \\caption{Third subfigure}\n        \\label{fig:sub3}\n    \\end{subfigure}\n    \\hfill\n    \\begin{subfigure}{0.45\\textwidth}\n        \\includegraphics[width=\\textwidth]{example-image}\n        \\caption{Fourth subfigure}\n        \\label{fig:sub4}\n    \\end{subfigure}\n    \\caption{Grid layout with four subfigures}\n    \\label{fig:grid}\n\\end{figure}\n\nFigure~\\ref{fig:grid} shows a 2×2 grid layout, with individual subfigures \\ref{fig:sub1} through \\ref{fig:sub4}.\n\n\\section{Rotated and Scaled Image}\n\n\\begin{figure}[H]\n    \\centering\n    \\includegraphics[angle=45, scale=0.5]{example-image}\n    \\caption{Rotated and scaled image}\n    \\label{fig:rotated}\n\\end{figure}\n\n\\section{Conclusion}\n\nThis document demonstrated various image handling techniques in LaTeX, from basic inclusion to advanced layouts.\n\n\\listoffigures\n\n\\end{document}"} />

<RenderedOutput title="Rendered output">
  <LatexPreview src="/images/rendered/learn-latex-how-to-working-with-images-21/page-1.svg" alt="Compiled PDF page 1 from complete-image-document.tex" caption="Page 1 of 3. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />

  <LatexPreview src="/images/rendered/learn-latex-how-to-working-with-images-21/page-2.svg" alt="Compiled PDF page 2 from complete-image-document.tex" caption="Page 2 of 3. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />

  <LatexPreview src="/images/rendered/learn-latex-how-to-working-with-images-21/page-3.svg" alt="Compiled PDF page 3 from complete-image-document.tex" caption="Page 3 of 3. Generated from the shown source with pdfLaTeX in the pinned LaTeXCloud TeX Live 2026 environment." width={595.276} height={841.89} />
</RenderedOutput>

## Next Steps

Now that you've mastered image handling:

<CardGroup cols={2}>
  <Card title="Creating Tables" icon="table" href="/learn/latex/how-to/professional-tables">
    Learn to create professional tables
  </Card>

  <Card title="TikZ Graphics" icon="draw-polygon" href="/learn/latex/how-to/tikz-diagrams">
    Create diagrams with TikZ
  </Card>

  <Card title="Managing Large Documents" icon="folder-open" href="/learn/latex/how-to/large-documents">
    Handle images in multi-file projects
  </Card>

  <Card title="Troubleshooting" icon="bug" href="/learn/latex/how-to/fixing-compilation-errors">
    Fix common image-related errors
  </Card>
</CardGroup>

***

<Info>
  **Pro tip**: Always keep high-resolution originals of your images. You can create lower-resolution versions for drafts and switch to high-resolution for final output using conditional inclusion.
</Info>
