# ImageCropper (/docs/image-cropper)





`ImageCropper` shows an image under a selection. Drag the selection to move it, pull its handles to resize it, and drag the image around it to pan. Zoom with the wheel or a pinch, from the keyboard, or with the controls. `src` takes a URL or a `Blob`, so a file the user just picked can go straight in. Read the result through `ImageCropper.Context`: `getCroppedImage()` draws the crop and resolves a `Blob`, and `getCropData()` gives the crop in the image's own pixels, for a server to cut.

```tsx
import { ImageCropper } from '@42-central/ui-react/image-cropper';

<ImageCropper src={file} shape="circle" withControls>
  <ImageCropper.Context>
    {(api) => <Button onClick={async () => upload(await api.getCroppedImage())}>Save</Button>}
  </ImageCropper.Context>
</ImageCropper>
```

<Callout type="warn" title="Built on a preview Ark component">
  The cropper wraps Ark UI's image cropper, which Ark 5.39 marks as a *preview*: its API may change in a minor Ark release. The kit's props stay the same when it does; `ImageCropper.Context` hands you Ark's own API, so code that reads it may need to follow.
</Callout>

## Playground [#playground]

<story.Playground />

### Full prop browser [#full-prop-browser]

<story.WithControl />

## Basic [#basic]

With no `ratio`, the selection resizes freely. Everything outside it is dimmed.

<Preview code="`<ImageCropper src={photo} crossOrigin=&#x22;anonymous&#x22; />`">
  <BasicDemo />
</Preview>

A URL from another origin needs `crossOrigin="anonymous"`, and the server must send CORS headers, for the export to read its pixels. A `Blob` or a same-origin URL needs neither.

## Circle [#circle]

`shape="circle"` is the avatar crop: the selection is a circle, always 1:1, and only its four edge handles show. The export is still a square image. Mask it with `rounded-full` wherever you show it.

<Preview code="`<ImageCropper src={portrait} crossOrigin=&#x22;anonymous&#x22; shape=&#x22;circle&#x22; />`">
  <CircleDemo />
</Preview>

## Fixed ratio [#fixed-ratio]

`ratio` locks the selection's width over height. It takes the same values as `Image` and `AspectRatio`: a number (`16 / 9`) or a string (`"16/9"`). When it changes, the selection reshapes around its center. Rule-of-thirds lines fade in over the selection while you drag, resize or pan; `withGrid={false}` turns them off.

<Preview code="&#x22;const [ratio, setRatio] = useState('16/9');\n\n<SegmentGroup data={['1/1', '4/3', '16/9']} value={ratio} onChange={setRatio} />\n<ImageCropper src={photo} ratio={ratio} />&#x22;">
  <RatioDemo />
</Preview>

## Controlled zoom [#controlled-zoom]

`zoom`, `rotation` and `flip` can each be controlled, or seeded with `defaultZoom`, `defaultRotation` and `defaultFlip`. Their callbacks hand you the value itself: `onZoomChange(zoom)`, `onRotationChange(degrees)`, `onFlipChange({ horizontal, vertical })`. `onCropChange(crop)` reports the selection, in pixels of the viewport. Zoom runs from `minZoom` (1, the image fitted) to `maxZoom` (5).

<Preview code="&#x22;const [zoom, setZoom] = useState(1.5);\n\n<ImageCropper src={photo} zoom={zoom} onZoomChange={setZoom} />\n<Slider aria-label={['Zoom']} min={1} max={5} step={0.01} value={zoom} onChange={setZoom} />\n<output>{zoom.toFixed(2)}×</output>&#x22;">
  <ControlledZoomDemo />
</Preview>

Ark applies a new `zoom` prop when it changes, but it doesn't hold the image at it: a wheel or a pinch zooms first and reports after. So always pair `zoom` with `onZoomChange`, as here, and the two stay in step.

## Export [#export]

`ImageCropper.Context` passes its render function Ark's cropper API. `getCroppedImage()` draws the crop, with the rotation and flips applied, to a canvas, and resolves a PNG `Blob`. Pass `{ type: 'image/jpeg', quality: 0.9 }` for a JPEG, `maxSize` to scale it down, or `output: 'dataUrl'` for a string. It resolves `null` if the image hasn't loaded, or if a cross-origin image was loaded without CORS. The crop is exported at the image's own resolution, not the size it has on screen.

With a `ratio`, or `shape="circle"`, the export holds that ratio to the pixel: a circle is always square, never 511 × 512. Ark sizes the canvas from the image's rounded size on screen, so a locked crop can land a pixel off; when it does, the kit exports it again without loss and redraws it at the exact size, then encodes it once as you asked. `useImageCropperContext()` returns the same API, for a part of your own.

<Preview code="&#x22;<ImageCropper src={photo} crossOrigin=\&#x22;anonymous\&#x22; ratio=\&#x22;4/3\&#x22;>\n  <ImageCropper.Context>\n    {(api) => (\n      <Button\n        onClick={async () => {\n          const blob = await api.getCroppedImage({ maxSize: { width: 1200, height: 1200 } });\n          if (blob instanceof Blob) setCrop(blob);\n        }}\n      >\n        Crop\n      </Button>\n    )}\n  </ImageCropper.Context>\n</ImageCropper>\n\nconst url = useObjectUrl(crop);\n<Image src={url} alt=\&#x22;The cropped photo\&#x22; />\n<Button asChild startSlot={<Download />}>\n  <a href={url} download=\&#x22;crop.png\&#x22;>Download</a>\n</Button>&#x22;">
  <ExportDemo />
</Preview>

[`useObjectUrl`](/docs/utilities/files#useobjecturl), from `@42-central/ui-react`, turns a `Blob` into a URL for an `<img>` or a link, and revokes it when the blob changes or the component unmounts. It is also how `ImageCropper` shows a `Blob` `src`: only a raster image (re-typed) or an SVG (as a `data:` URL) gets a URL, so a picked file that isn't an image never loads, and never runs as your app. A `Blob` with no type needs one, or a `File`'s name, to be shown.

To crop on the server instead, send the original file and `api.getCropData()`: `{ x, y, width, height }` in the image's own pixels, plus `rotate`, `flipX` and `flipY`. Under a rotation that's the bounding box of the crop; `corners` has the exact four points.

## Controls [#controls]

`withControls` adds a row under the image: rotate left and right by 90°, flip horizontally and vertically, a zoom slider, and reset. `ImageCropper.Controls` is the same row, for a cropper you compose yourself.

<Preview code="`<ImageCropper src={photo} withControls />`">
  <ControlsDemo />
</Preview>

### Icons [#icons]

`icons` replaces the control icons, per instance, by the same names as the buttons' `translations`: `rotateLeft`, `rotateRight`, `flipHorizontal`, `flipVertical`, `zoomOut`, `zoomIn` and `reset`. A key left out (or set to `undefined`) keeps the kit's icon, so swap only the ones you need. It goes on `ImageCropper` or `ImageCropper.Root`, and reaches an `ImageCropper.Controls` anywhere inside.

Your icon is drawn as given: the buttons size it (20px, 16px at the ends of the zoom slider) but never restroke it, so add `className={iconStroke}` (from `@42-central/ui-react`) for the kit's 1.5px line. None of the defaults mirrors under right-to-left, since none points along the inline axis; if yours does, add `rtl:-scale-x-100` to it yourself.

<Preview code="&#x22;import { iconStroke } from '@42-central/ui-react';\nimport { Minus, Plus, RotateCcwSquare, RotateCwSquare, Undo2 } from 'lucide-react';\n\n<ImageCropper\n  src={photo}\n  withControls\n  icons={{\n    rotateLeft: <RotateCcwSquare className={iconStroke} />,\n    rotateRight: <RotateCwSquare className={iconStroke} />,\n    zoomOut: <Minus className={iconStroke} />,\n    zoomIn: <Plus className={iconStroke} />,\n    reset: <Undo2 className={iconStroke} />,\n  }}\n/>&#x22;">
  <IconsDemo />
</Preview>

## Color [#color]

The selection's edge, its handles, its focus ring and the zoom slider take `color`, `brand` by default. Outside the selection the image is dimmed and lightly blurred, like the page behind a [Modal](/docs/modal), with the selection cut out of the dim as a real rectangle or circle.

<Preview code="`<ImageCropper src={photo} color=&#x22;green&#x22; withControls />`">
  <ColorDemo />
</Preview>

## Composable parts [#composable-parts]

`<ImageCropper>` is a ready-made arrangement of parts. Build your own when you need the controls elsewhere, or your own handles:

```tsx
<ImageCropper.Root ratio={1} onCropChange={setCrop}>
  <ImageCropper.Viewport radius="md" className="h-80">
    <ImageCropper.Image src={file} />
    <ImageCropper.Selection />
  </ImageCropper.Viewport>
  <ImageCropper.Controls />
  <ImageCropper.Context>{(api) => <SaveButton api={api} />}</ImageCropper.Context>
</ImageCropper.Root>
```

`useImageCropperContext()` returns the same API as `ImageCropper.Context`, for a component inside the root.

## Right-to-left [#right-to-left]

The cropper's direction comes from the locale. Under `IntlProvider locale="ar-EG"` the controls row runs right to left, every label is translated, and every number announced uses Arabic-Indic digits.

<Preview code="&#x22;<IntlProvider locale=\&#x22;ar-EG\&#x22;>\n  <div dir=\&#x22;rtl\&#x22; lang=\&#x22;ar\&#x22;>\n    <ImageCropper src={photo} withControls translations={arabic} />\n  </div>\n</IntlProvider>&#x22;">
  <DirectionDemo />
</Preview>

The image itself and the crop don't mirror: the crop is a rectangle in the image's own space, so its handles stay where they are on the image. The arrow keys do change, and that's Ark's behavior rather than the kit's: on a right-to-left page Ark swaps <kbd>←</kbd> and <kbd>→</kbd>, as it does for a one-dimensional slider. <kbd>←</kbd> moves the selection to the right, and <kbd>Alt</kbd> + <kbd>←</kbd> widens it. Up and down are unchanged.

## API [#api]

<TypeTable
  type="{
  src: {
    type: &#x22;string | Blob&#x22;,
    required: true,
    description: &#x22;The image: a URL, or a Blob / File, shown through an object URL that's revoked when it changes.&#x22;,
  },
  crossOrigin: {
    type: '&#x22;anonymous&#x22; | &#x22;use-credentials&#x22; | &#x22;&#x22;',
    description: &#x22;Set it on a cross-origin URL, served with CORS, so getCroppedImage can read its pixels.&#x22;,
  },
  ratio: {
    type: 'number | &#x22;w/h&#x22;',
    description: &#x22;Locks the selection's width over height. Free when unset.&#x22;,
  },
  shape: {
    type: '&#x22;rectangle&#x22; | &#x22;circle&#x22;',
    default: '&#x22;rectangle&#x22;',
    description: &#x22;A circle is always 1:1, and exports a square.&#x22;,
  },
  &#x22;zoom / defaultZoom / onZoomChange&#x22;: {
    type: &#x22;number / number / (zoom: number) => void&#x22;,
    default: &#x22;1&#x22;,
    description: &#x22;The zoom, from minZoom to maxZoom.&#x22;,
  },
  &#x22;minZoom / maxZoom&#x22;: { type: &#x22;number&#x22;, default: &#x22;1 / 5&#x22;, description: &#x22;The zoom range. 1 is the image fitted.&#x22; },
  &#x22;rotation / defaultRotation / onRotationChange&#x22;: {
    type: &#x22;number / number / (degrees: number) => void&#x22;,
    default: &#x22;0&#x22;,
    description: &#x22;The rotation, in degrees.&#x22;,
  },
  &#x22;flip / defaultFlip / onFlipChange&#x22;: {
    type: &#x22;{ horizontal: boolean; vertical: boolean }&#x22;,
    default: &#x22;both false&#x22;,
    description: &#x22;Mirrors the image.&#x22;,
  },
  onCropChange: {
    type: &#x22;(crop: { x, y, width, height }) => void&#x22;,
    description: &#x22;Fires as the selection moves or resizes, in pixels of the viewport.&#x22;,
  },
  initialCrop: {
    type: &#x22;{ x, y, width, height }&#x22;,
    description: &#x22;Where the selection starts, in pixels of the viewport. Centered and sized to fit by default.&#x22;,
  },
  &#x22;minWidth / minHeight / maxWidth / maxHeight&#x22;: {
    type: &#x22;number&#x22;,
    default: &#x22;40 / 40 / ∞ / ∞&#x22;,
    description: &#x22;The selection's size limits, in pixels of the viewport.&#x22;,
  },
  fixedCropArea: {
    type: &#x22;boolean&#x22;,
    default: &#x22;false&#x22;,
    description: &#x22;The selection stays put; dragging and the arrow keys pan the image under it instead.&#x22;,
  },
  &#x22;zoomStep / zoomSensitivity&#x22;: {
    type: &#x22;number&#x22;,
    default: &#x22;0.1 / 2&#x22;,
    description: &#x22;The zoom per wheel step or keypress, and how fast a pinch zooms.&#x22;,
  },
  &#x22;nudgeStep / nudgeStepShift / nudgeStepCtrl&#x22;: {
    type: &#x22;number&#x22;,
    default: &#x22;1 / 10 / 50&#x22;,
    description: &#x22;Pixels an arrow key moves the selection, alone, with Shift, and with Ctrl / ⌘.&#x22;,
  },
  radius: {
    type: '&#x22;none&#x22; | &#x22;xs&#x22; | &#x22;sm&#x22; | &#x22;md&#x22; | &#x22;lg&#x22; | &#x22;xl&#x22; | &#x22;full&#x22;',
    default: '&#x22;xs&#x22;',
    description: &#x22;The viewport's corners, from the media scale.&#x22;,
  },
  withGrid: {
    type: &#x22;boolean&#x22;,
    default: &#x22;true&#x22;,
    description: &#x22;Rule-of-thirds lines in the selection, faded in while it's dragged, resized or panned.&#x22;,
  },
  color: {
    type: &#x22;Color&#x22;,
    default: '&#x22;brand&#x22;',
    description: &#x22;The palette of the selection's edge, handles, focus ring and zoom slider.&#x22;,
  },
  withControls: {
    type: &#x22;boolean&#x22;,
    default: &#x22;false&#x22;,
    description: &#x22;The zoom slider and the rotate, flip and reset buttons, under the image.&#x22;,
  },
  translations: { type: &#x22;ImageCropperTranslations&#x22;, description: &#x22;See Internationalization.&#x22; },
  icons: {
    type: &#x22;ImageCropperIcons&#x22;,
    description: &#x22;Replaces the control icons: rotateLeft, rotateRight, flipHorizontal, flipVertical, zoomOut, zoomIn, reset. A missing or undefined key keeps the default.&#x22;,
  },
  className: { type: &#x22;string&#x22;, description: &#x22;Applies to the root.&#x22; },
  classNames: {
    type: &#x22;{ viewport?, image?, selection?, controls? }&#x22;,
    description: &#x22;Per-part classes.&#x22;,
  },
  testId: {
    type: &#x22;string&#x22;,
    description: &#x22;Renders as data-testid on the root. See [Testing](/docs/testing).&#x22;,
  },
  children: {
    type: &#x22;ReactNode&#x22;,
    description: &#x22;Rendered last, inside the root: an ImageCropper.Context for the export, your own buttons.&#x22;,
  },
}"
/>

`ImageCropper.Root` takes everything except `src`, `crossOrigin`, `radius`, `withGrid`, `withControls` and `classNames`.

### Parts [#parts]

| Part                     | Renders               | Notes                                                                                                                                   |
| ------------------------ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `ImageCropper.Root`      | `<div role="group">`  | State, translations and the locale. Takes `asChild`.                                                                                    |
| `ImageCropper.Viewport`  | `<div>`               | The dark, clipped frame. Takes the pan, wheel and pinch. `radius`, `asChild`.                                                           |
| `ImageCropper.Image`     | `<img aria-hidden>`   | `src` as a URL or a `Blob`. Fades in once measured.                                                                                     |
| `ImageCropper.Selection` | `<div role="slider">` | The crop and its eight handles, the grid (`withGrid`, on by default), and, just before it, the `aria-hidden` dim with the crop cut out. |
| `ImageCropper.Handle`    | `<div aria-hidden>`   | One handle, by `position` (`n`, `ne`, … `nw`). Takes `asChild`.                                                                         |
| `ImageCropper.Grid`      | `<div aria-hidden>`   | Two thirds lines along `axis`. Takes `asChild`.                                                                                         |
| `ImageCropper.Controls`  | `<div role="group">`  | Rotate, flip, zoom and reset.                                                                                                           |
| `ImageCropper.Context`   | Your render function  | Ark's API: `zoom`, `rotation`, `flip`, `crop`, `setZoom`, `rotateBy`, `flipHorizontally`, `reset`, `getCroppedImage`, `getCropData`, …  |

## Accessibility [#accessibility]

* **The selection is a 2D slider**, the pattern Ark follows: `role="slider"` with `aria-roledescription="2d slider"`, named "Crop selection (rectangle)" or "(circle)". Its `aria-valuetext` says where it is and how big ("Position X 120px, Y 48px. Size 320px by 240px."), and its description says how to use it. It's in the tab order.
* **The cropper is a named group.** Its description sums up the zoom, the rotation and the crop, and is announced politely as it changes. While the image loads the group is `aria-busy`.
* **Every gesture has a keyboard equivalent**, and every control a single-pointer one ([WCAG 2.5.1](https://www.w3.org/WAI/WCAG22/Understanding/pointer-gestures.html), [2.5.7](https://www.w3.org/WAI/WCAG22/Understanding/dragging-movements.html)). With the selection focused:

| Key                                                 | Does                                                                                                                            |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| <kbd>←</kbd> <kbd>→</kbd> <kbd>↑</kbd> <kbd>↓</kbd> | Move the selection 1px. <kbd>←</kbd> and <kbd>→</kbd> are swapped on a right-to-left page, see [Right-to-left](#right-to-left). |
| <kbd>Shift</kbd> + arrows                           | Move it 10px.                                                                                                                   |
| <kbd>Ctrl</kbd> / <kbd>⌘</kbd> + arrows             | Move it 50px.                                                                                                                   |
| <kbd>Alt</kbd> + <kbd>←</kbd> <kbd>→</kbd>          | Narrow / widen it, from its right edge.                                                                                         |
| <kbd>Alt</kbd> + <kbd>↑</kbd> <kbd>↓</kbd>          | Shorten / lengthen it, from its bottom edge.                                                                                    |
| <kbd>+</kbd> / <kbd>−</kbd>                         | Zoom in / out a step.                                                                                                           |
| <kbd>Tab</kbd>                                      | On to the controls.                                                                                                             |

With `fixedCropArea`, the arrow keys pan the image instead.

* **The controls** are buttons named from `translations`, 44px each, above the [WCAG 2.5.8](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html) minimum. The flips are toggle buttons with `aria-pressed`. The zoom slider is named "Zoom" and reads its value as a percent.
* **The image** is hidden from assistive technology: the group's description and the selection's value say what's selected.
* **Handles** are for the pointer only (`aria-hidden`); <kbd>Alt</kbd> + arrows resizes from the keyboard. On a touch screen their hit area grows from 24px to 44px, around the same small mark.
* **Forced colors.** In Windows High Contrast the dim outside the selection steps aside (it would paint the system background over the image), and the selection's border, its handles and the focus outline are repainted in system colors.
* **Reduced motion.** The image fades in once it has loaded, the grid fades in while you drag, and a held handle grows slightly, all on the kit's `--duration-*` and `--ease-standard` tokens. Under `prefers-reduced-motion` each is instant. Dragging, panning and zooming follow your input directly.

## Internationalization [#internationalization]

Every string the cropper shows or announces is in `translations`, Ark's included. Numbers arrive already formatted with `Intl.NumberFormat` for the locale from [`IntlProvider`](/docs/intl): pixels as plain numbers, the zoom as a percent, the rotation in degrees.

| Key                        | Default                                                                                                                                                                 |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `label`                    | `"Image cropper"`                                                                                                                                                       |
| `roleDescription`          | `"image cropper"`                                                                                                                                                       |
| `loading`                  | `"Loading the image"`                                                                                                                                                   |
| `preview`                  | ``({ zoom, rotation, x, y, width, height }) => `Zoom ${zoom}, rotated ${rotation}. Crop at ${x}px from the left and ${y}px from the top, ${width}px by ${height}px.` `` |
| `selectionLabel`           | ``(shape) => `Crop selection (${shape})` ``                                                                                                                             |
| `selectionRoleDescription` | `"2d slider"`                                                                                                                                                           |
| `selectionInstructions`    | `"Use the arrow keys to move the crop. Hold Alt with the arrow keys to resize it. Press plus or minus to zoom."`                                                        |
| `selectionValue`           | ``({ shape, x, y, width, height }) => `Position X ${x}px, Y ${y}px. Size ${width}px by ${height}px.` `` (a circle reads its diameter)                                   |
| `controlsLabel`            | `"Crop controls"`                                                                                                                                                       |
| `zoomLabel`                | `"Zoom"`                                                                                                                                                                |
| `zoomValue`                | `(percent) => percent`                                                                                                                                                  |
| `rotateLeftLabel`          | `"Rotate left"`                                                                                                                                                         |
| `rotateRightLabel`         | `"Rotate right"`                                                                                                                                                        |
| `flipHorizontalLabel`      | `"Flip horizontally"`                                                                                                                                                   |
| `flipVerticalLabel`        | `"Flip vertically"`                                                                                                                                                     |
| `resetLabel`               | `"Reset"`                                                                                                                                                               |

```tsx
<ImageCropper
  src={file}
  translations={{
    label: t('cropper.label'),
    selectionValue: ({ x, y, width, height }) => t('cropper.selection', { x, y, width, height }),
    zoomValue: (percent) => t('cropper.zoom', { percent }),
  }}
/>
```

## Testing [#testing]

`testId` lands on the root, the `role="group"` named by `translations.label`. Find the controls by role and name:

```tsx
render(<ImageCropper src={file} withControls onRotationChange={onRotationChange} />);
await user.click(screen.getByRole('button', { name: 'Rotate right' }));
await waitFor(() => expect(onRotationChange).toHaveBeenLastCalledWith(90));
```

Two things don't work in jsdom. It lays nothing out, so Ark never measures the viewport: the selection stays `visibility: hidden` (find it by `[data-part="selection"]`), has no size, and ignores its keys. And it has no canvas, so `getCroppedImage()` can't run: test your export handler with a stubbed API, and the crop itself in a real browser. The cropper's state updates a tick after an event, so wait for callbacks with `waitFor`.
