ImageCropper
Pick the part of an image to keep. Drag and resize the selection, zoom, rotate and flip the image, then export the crop as a Blob or as coordinates for your server.
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.
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>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.
Playground
Component
Dir
Presets
Props
Code
<Component />Full prop browser
Basic
With no ratio, the selection resizes freely. Everything outside it is dimmed.
Code
<ImageCropper src={photo} crossOrigin="anonymous" />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
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.
Code
<ImageCropper src={portrait} crossOrigin="anonymous" shape="circle" />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.
Code
const [ratio, setRatio] = useState('16/9');
<SegmentGroup data={['1/1', '4/3', '16/9']} value={ratio} onChange={setRatio} />
<ImageCropper src={photo} ratio={ratio} />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).
Code
const [zoom, setZoom] = useState(1.5);
<ImageCropper src={photo} zoom={zoom} onZoomChange={setZoom} />
<Slider aria-label={['Zoom']} min={1} max={5} step={0.01} value={zoom} onChange={setZoom} />
<output>{zoom.toFixed(2)}×</output>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
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.
Code
<ImageCropper src={photo} crossOrigin="anonymous" ratio="4/3">
<ImageCropper.Context>
{(api) => (
<Button
onClick={async () => {
const blob = await api.getCroppedImage({ maxSize: { width: 1200, height: 1200 } });
if (blob instanceof Blob) setCrop(blob);
}}
>
Crop
</Button>
)}
</ImageCropper.Context>
</ImageCropper>
const url = useObjectUrl(crop);
<Image src={url} alt="The cropped photo" />
<Button asChild startSlot={<Download />}>
<a href={url} download="crop.png">Download</a>
</Button>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
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.
Code
<ImageCropper src={photo} withControls />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.
Code
import { iconStroke } from '@42-central/ui-react';
import { Minus, Plus, RotateCcwSquare, RotateCwSquare, Undo2 } from 'lucide-react';
<ImageCropper
src={photo}
withControls
icons={{
rotateLeft: <RotateCcwSquare className={iconStroke} />,
rotateRight: <RotateCwSquare className={iconStroke} />,
zoomOut: <Minus className={iconStroke} />,
zoomIn: <Plus className={iconStroke} />,
reset: <Undo2 className={iconStroke} />,
}}
/>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, with the selection cut out of the dim as a real rectangle or circle.
Code
<ImageCropper src={photo} color="green" withControls />Composable parts
<ImageCropper> is a ready-made arrangement of parts. Build your own when you need the controls elsewhere, or your own handles:
<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
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.
Code
<IntlProvider locale="ar-EG">
<div dir="rtl" lang="ar">
<ImageCropper src={photo} withControls translations={arabic} />
</div>
</IntlProvider>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 ← and →, as it does for a one-dimensional slider. ← moves the selection to the right, and Alt + ← widens it. Up and down are unchanged.
API
Prop
Type
ImageCropper.Root takes everything except src, crossOrigin, radius, withGrid, withControls and classNames.
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
- The selection is a 2D slider, the pattern Ark follows:
role="slider"witharia-roledescription="2d slider", named "Crop selection (rectangle)" or "(circle)". Itsaria-valuetextsays 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, 2.5.7). With the selection focused:
| Key | Does |
|---|---|
| ← → ↑ ↓ | Move the selection 1px. ← and → are swapped on a right-to-left page, see Right-to-left. |
| Shift + arrows | Move it 10px. |
| Ctrl / ⌘ + arrows | Move it 50px. |
| Alt + ← → | Narrow / widen it, from its right edge. |
| Alt + ↑ ↓ | Shorten / lengthen it, from its bottom edge. |
| + / − | Zoom in / out a step. |
| Tab | 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 minimum. The flips are toggle buttons witharia-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); Alt + 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-standardtokens. Underprefers-reduced-motioneach is instant. Dragging, panning and zooming follow your input directly.
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: 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" |
<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
testId lands on the root, the role="group" named by translations.label. Find the controls by role and name:
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.
Changelog
- #510
in-*and unnamedgroup-*selectors are scoped to the component's own attribute, so nested or wrapped components no longer pick up an ancestor's orientation, shape, invalid or hover state
- #464
No computed-style read on mount in production: the RTL direction check runs in development only
- #355
New
ImageCropperwith aratioorshape="circle", a grid while dragging, andwithControlsfor zoom, rotate, flip and reset (glyphs swappable throughicons);getCroppedImage()exports at exactly the locked ratio
Compare
A before/after slider. Two images share one box, and a handle wipes between them. Drag it, press anywhere, or use the arrow keys.
Camera
Take a photo in the page. A live viewfinder with a framing guide, a shutter, a camera switch, and a panel for every state, from the first permission prompt to the steps that undo a refusal. The photo comes back as a File.