# Image

An image with loading and failure states, and an optional fullscreen preview with zoom, rotation and a gallery.

Page: https://sui.draco.dev/docs/components/image

### Example: image-demo

```tsx
"use client";
import {
  Image,
  ImageGroup,
  imageLabelsZhCN,
} from "@workspace/ui/components/image";
import type { ExampleProps } from "../types";

const colors = ["#70866A", "#648493", "#BC6C73"];
const images = colors.map(
  (color, index) =>
    "data:image/svg+xml," +
    encodeURIComponent(
      `<svg xmlns="http://www.w3.org/2000/svg" width="960" height="640" viewBox="0 0 960 640"><rect width="960" height="640" fill="${color}"/><circle cx="${240 + index * 100}" cy="240" r="180" fill="#ffffff" opacity=".4"/><path d="M0 560L960 180" stroke="#ffffff" stroke-width="40" opacity=".6"/><text x="60" y="600" font-family="sans-serif" font-size="56" fill="white">SUI ${index + 1}</text></svg>`,
    ),
);

export default function Example({ locale }: ExampleProps) {
  const chinese = locale === "zh-CN";
  const labels = chinese ? imageLabelsZhCN : undefined;
  return (
    <ImageGroup labels={labels}>
      <div className="grid w-full grid-cols-3 gap-3">
        {images.map((image, index) => (
          <Image
            key={image}
            src={image}
            alt={
              chinese ? `示例图案 ${index + 1}` : `Example pattern ${index + 1}`
            }
            labels={labels}
            className="aspect-3/2 w-full rounded-xl"
          />
        ))}
      </div>
    </ImageGroup>
  );
}
```

## Installation

```bash
npx shadcn@latest add @sui/image
```

With pnpm, Yarn or Bun, use `pnpm dlx`, `yarn dlx` or `bunx --bun` in place of `npx`, and `pnpm add`, `yarn add` or `bun add` in place of `npm install`.

Install with the shadcn CLI or use the shared `@workspace/ui` package. Follow the [installation guide](/docs/installation) to configure the registry, load styles, and choose import aliases.

  Image installs as `components/ui/image/index.tsx`. If you installed it
  from SUI 5.4 or earlier, delete the old `components/ui/image.tsx` after
  updating: a file beside the folder wins over its index, so imports would
  keep the old version. See [Update installed
  source](/docs/registry#updating-source).

## Usage

```tsx
import { Image, ImageGroup } from "@workspace/ui/components/image";

// One image that opens a fullscreen preview
<Image src="/photos/cover.jpg" alt="Cover" width={240} height={160} preview />

// A gallery: clicking any image previews them all
<ImageGroup>
  {photos.map((photo) => (
    <Image key={photo.id} src={photo.thumb} alt={photo.name} preview={{ src: photo.full }} />
  ))}
</ImageGroup>
```

## Image

`Image` renders a picture in a box sized by `width` and `height` (numbers are pixels) or by `className`. `fit` sets `object-fit` and defaults to `cover`. While loading, a pulsing placeholder fills the box; if loading fails, `fallback` replaces it, or a default icon and the `error` label. The box exposes `data-state` as `loading`, `ready` or `error`. Other `<img>` attributes such as `loading="lazy"` pass through.

## Preview

`preview` is off by default, so an image stays a plain picture. `preview` turns the image into a button that opens a fullscreen preview; its accessible name comes from `labels.preview(alt)`. Pass an object to preview a larger `src`, or to control the preview with `open`, `defaultOpen` and `onOpenChange`. `container` chooses the Portal container.

Inside the preview, wheel and pinch gestures zoom, dragging pans, and the toolbar zooms, rotates and resets. Arrow keys navigate, `+`/`-` zoom and `0` resets. Loading failures offer a retry. The preview uses the shared [Dialog](/docs/components/dialog) for focus management and dismissal.

### Example: image-fallback

```tsx
"use client";
import { Image, imageLabelsZhCN } from "@workspace/ui/components/image";
import type { ExampleProps } from "../types";

const photo =
  "data:image/svg+xml," +
  encodeURIComponent(
    '<svg xmlns="http://www.w3.org/2000/svg" width="480" height="320" viewBox="0 0 480 320"><rect width="480" height="320" fill="#648493"/><circle cx="160" cy="140" r="90" fill="#ffffff" opacity=".4"/></svg>',
  );

export default function Example({ locale }: ExampleProps) {
  const chinese = locale === "zh-CN";
  const labels = chinese ? imageLabelsZhCN : undefined;
  return (
    <div className="flex flex-wrap gap-4">
      <Image
        src={photo}
        alt={chinese ? "可预览" : "Previewable"}
        width={180}
        height={120}
        preview
        labels={labels}
        className="rounded-xl"
      />
      <Image
        src="/missing-photo.png"
        alt={chinese ? "加载失败" : "Failed to load"}
        width={180}
        height={120}
        labels={labels}
        className="rounded-xl"
      />
      <Image
        src="/missing-photo.png"
        alt={chinese ? "自定义占位" : "Custom fallback"}
        width={180}
        height={120}
        fallback={
          <span className="flex size-full items-center justify-center bg-muted font-medium text-muted-foreground text-sm">
            {chinese ? "暂无图片" : "No photo yet"}
          </span>
        }
        className="rounded-xl"
      />
    </div>
  );
}
```

## Gallery

`ImageGroup` turns the Images inside it into one gallery, without rendering a wrapper element. Clicking an image opens the preview on that image, with navigation and thumbnails in document order. Images take part unless they set `preview={false}`, and each one's `preview.src` is used when present. Control the group's preview through `preview={{ open, onOpenChange, index, onIndexChange }}`, with zero-based indexes.

## Preview without thumbnails

`ImagePreview` is the fullscreen viewer on its own, for opening images from other controls. It takes `images` (one or more URLs, or `{ src, alt }` items), `open`, `onOpenChange`, and an optional controlled `index` with `onIndexChange` or an uncontrolled `initialIndex`. Opening an uncontrolled preview restores `initialIndex`. An empty list renders nothing.

### Example: image-preview-controlled

```tsx
"use client";
import { Button } from "@workspace/ui/components/button";
import { ImagePreview, imageLabelsZhCN } from "@workspace/ui/components/image";
import { useState } from "react";
import type { ExampleProps } from "../types";

const colors = ["#70866A", "#648493", "#BC6C73"];
const images = colors.map(
  (color, index) =>
    "data:image/svg+xml," +
    encodeURIComponent(
      `<svg xmlns="http://www.w3.org/2000/svg" width="960" height="640" viewBox="0 0 960 640"><rect width="960" height="640" fill="${color}"/><circle cx="${240 + index * 100}" cy="240" r="180" fill="#ffffff" opacity=".4"/><path d="M0 560L960 180" stroke="#ffffff" stroke-width="40" opacity=".6"/><text x="60" y="600" font-family="sans-serif" font-size="56" fill="white">SUI ${index + 1}</text></svg>`,
    ),
);

export default function Example({ locale }: ExampleProps) {
  const chinese = locale === "zh-CN";
  const [open, setOpen] = useState(false);
  const [index, setIndex] = useState(0);
  return (
    <div className="grid w-full gap-4">
      <div className="flex flex-wrap gap-2">
        {images.map((image, imageIndex) => (
          <Button
            key={image}
            variant="outline"
            onClick={() => {
              setIndex(imageIndex);
              setOpen(true);
            }}
          >
            {chinese
              ? `打开第 ${imageIndex + 1} 张`
              : `Open image ${imageIndex + 1}`}
          </Button>
        ))}
      </div>
      <output className="text-muted-foreground text-sm" aria-live="polite">
        {chinese
          ? `选中索引：${index}（从 0 开始）`
          : `Selected index: ${index} (zero-based)`}
      </output>
      <ImagePreview
        images={images}
        open={open}
        onOpenChange={setOpen}
        index={index}
        onIndexChange={setIndex}
        alt={chinese ? "几何图案" : "Geometric pattern"}
        labels={chinese ? imageLabelsZhCN : undefined}
      />
    </div>
  );
}
```

## Labels and glass

`labels` customizes the preview button, toolbar, navigation, thumbnail and position announcements; pass `imageLabelsZhCN` for Chinese. Function labels receive one-based positions. `glass` and `frosted` on `Image`, `ImageGroup` or `ImagePreview` apply only to the preview's controls; the dialog, images and thumbnails keep their normal styles.

## API reference

### Image

| Prop | Type | Default / behavior |
| --- | --- | --- |
| `src`, `alt` | `string` | Required. |
| `width`, `height` | `number \| string` | Box size; numbers are pixels. |
| `fit` | `CSSProperties["objectFit"]` | `"cover"`. |
| `fallback` | `ReactNode` | Icon and `labels.error`. |
| `preview` | `boolean \| { src, open, defaultOpen, onOpenChange, container }` | `false`; inside ImageGroup, on unless `false`. |
| `labels` | `Partial<ImageLabels>` | English labels. |
| `glass`, `frosted` | `boolean \| GlassConfig`, `boolean` | `false`; preview controls only. |

### ImageGroup

| Prop | Type | Default / behavior |
| --- | --- | --- |
| `preview` | `{ open, onOpenChange, index, onIndexChange, container }` | Uncontrolled. |
| `alt` | `string` | Alt text for images without their own. |
| `labels`, `glass`, `frosted` | As Image | Applied to the shared preview. |

### ImagePreview

| Prop | Type | Default / behavior |
| --- | --- | --- |
| `images` | `ImagePreviewItem \| ImagePreviewItem[]` | Required URL(s) or `{ src, alt }` items. |
| `open` / `onOpenChange` | `boolean` / `(open: boolean) => void` | Required. |
| `index` / `initialIndex` | `number` | Controlled / `0`. |
| `onIndexChange` | `(index: number) => void` | Reports the zero-based index. |
| `alt` | `string` | `labels.defaultAlt`. |
| `container` | Portal container | Optional. |

The module exports `ImageProps`, `ImageGroupProps`, `ImagePreviewProps`, `ImagePreviewItem` and `ImageLabels`. The modal behavior is documented in the [Base UI Dialog API](https://base-ui.com/react/components/dialog).
