# Shadcn Image Cropper

An image cropper for covers, avatars and uploads. Drag and resize a selection over the image, or keep the frame still and pan the image under it. It supports fixed aspect ratios, circular framing, zoom, quarter turns and flips, full keyboard control, and `cropImage` turns the result into a PNG, JPEG or WebP file in the browser.

`image-cropper-demo.tsx`:

```tsx
import {
  ImageCropper,
  ImageCropperGrid,
  ImageCropperHandles,
  ImageCropperImage,
  ImageCropperSelection,
  ImageCropperViewport,
} from "@/components/ui/image-cropper";

const photo =
  "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&q=80&auto=format&fit=crop";

export default function ImageCropperDemo() {
  return (
    <ImageCropper
      aria-label="Photo"
      src={photo}
      className="max-w-md"
    >
      <ImageCropperViewport>
        <ImageCropperImage alt="Mountain range above the clouds" />
        <ImageCropperSelection>
          <ImageCropperGrid />
        </ImageCropperSelection>
        <ImageCropperHandles />
      </ImageCropperViewport>
    </ImageCropper>
  );
}
```

## Installation

```bash
npx shadcn@latest add @shadcnuikit/image-cropper1
```

This adds `components/ui/image-cropper.tsx`, the `button` component it depends on, and a demo file. Set up the registry once as described in [Shadcn CLI](https://shadcnuikit.com/docs/shadcn-cli). Image Cropper is free and installs without an API key.

### Manual installation

Install the dependencies and the `button` component:

```bash
npm install @ui-sdk/react@beta class-variance-authority lucide-react
npx shadcn@latest add button
```

Copy the source into `components/ui/image-cropper.tsx`:

`components/ui/image-cropper.tsx`:

```tsx
"use client";

import * as React from "react";
import type { VariantProps } from "class-variance-authority";
import {
  ImageCropper as ImageCropperPrimitive,
  ImageCropperFlip as ImageCropperFlipPrimitive,
  ImageCropperGrid as ImageCropperGridPrimitive,
  ImageCropperHandle as ImageCropperHandlePrimitive,
  ImageCropperImage as ImageCropperImagePrimitive,
  ImageCropperRotate as ImageCropperRotatePrimitive,
  ImageCropperSelection as ImageCropperSelectionPrimitive,
  ImageCropperViewport as ImageCropperViewportPrimitive,
  ImageCropperZoom as ImageCropperZoomPrimitive,
  createImageCropperController,
  type ImageCrop,
  type ImageCropperHandlePosition,
} from "@ui-sdk/react/image-cropper";
import { cropImage } from "@ui-sdk/react/image";
import {
  FlipHorizontal2Icon,
  FlipVertical2Icon,
  RotateCwIcon,
} from "lucide-react";

import { Button, buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";

type WithClassName<T> = Omit<T, "className"> & { className?: string };
type ButtonStyleProps = Pick<
  VariantProps<typeof buttonVariants>,
  "variant" | "size"
>;

const imageCropperHandlePositions = [
  "nw",
  "n",
  "ne",
  "e",
  "se",
  "s",
  "sw",
  "w",
] as const satisfies readonly ImageCropperHandlePosition[];

function ImageCropper({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperPrimitive>>) {
  return (
    <ImageCropperPrimitive
      className={cn(
        "flex w-full flex-col gap-3 data-disabled:opacity-60",
        className,
      )}
      {...props}
    />
  );
}

function ImageCropperViewport({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperViewportPrimitive>>) {
  return (
    <ImageCropperViewportPrimitive
      className={cn(
        "bg-muted relative w-full touch-none overflow-hidden rounded-lg border p-2 select-none",
        "data-[mode=box]:aspect-[var(--image-cropper-aspect-ratio,4/3)] data-[mode=frame]:aspect-square",
        "data-disabled:cursor-default! data-[mode=frame]:cursor-grab data-[mode=frame]:data-dragging:cursor-grabbing",
        "data-loading:animate-pulse",
        className,
      )}
      {...props}
    />
  );
}

function ImageCropperImage({
  className,
  crossOrigin = "anonymous",
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperImagePrimitive>>) {
  return (
    <ImageCropperImagePrimitive
      crossOrigin={crossOrigin}
      draggable={false}
      className={cn("max-w-none select-none data-loading:opacity-0", className)}
      {...props}
    />
  );
}

function ImageCropperSelection({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperSelectionPrimitive>>) {
  return (
    <ImageCropperSelectionPrimitive
      className={cn(
        "border border-white/90 shadow-[0_0_0_9999px_rgb(0_0_0/0.55)] outline-none",
        "focus-visible:ring-ring/60 transition-[box-shadow] focus-visible:ring-[3px]",
        "data-[mode=box]:cursor-move data-[mode=frame]:pointer-events-none data-[shape=circle]:rounded-full",
        "data-disabled:cursor-default",
        className,
      )}
      {...props}
    />
  );
}

function ImageCropperGrid({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperGridPrimitive>>) {
  return (
    <ImageCropperGridPrimitive
      className={cn(
        "pointer-events-none absolute inset-0 overflow-hidden opacity-0 transition-opacity duration-200 data-dragging:opacity-100 data-[shape=circle]:rounded-full",
        "before:absolute before:inset-y-0 before:left-1/3 before:w-1/3 before:border-x before:border-white/50",
        "after:absolute after:inset-x-0 after:top-1/3 after:h-1/3 after:border-y after:border-white/50",
        className,
      )}
      {...props}
    />
  );
}

function ImageCropperHandle({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperHandlePrimitive>>) {
  return (
    <ImageCropperHandlePrimitive
      className={cn(
        "border-primary bg-background absolute z-10 -translate-1/2 rounded-full border-2 shadow-sm outline-none",
        "focus-visible:ring-ring/60 transition-[box-shadow] focus-visible:ring-[3px]",
        "after:absolute after:-inset-2",
        "data-[position=ne]:size-3.5 data-[position=nw]:size-3.5 data-[position=se]:size-3.5 data-[position=sw]:size-3.5",
        "data-[position=n]:h-2 data-[position=n]:w-5 data-[position=s]:h-2 data-[position=s]:w-5",
        "data-[position=e]:h-5 data-[position=e]:w-2 data-[position=w]:h-5 data-[position=w]:w-2",
        "data-[position=n]:cursor-ns-resize data-[position=s]:cursor-ns-resize",
        "data-[position=e]:cursor-ew-resize data-[position=w]:cursor-ew-resize",
        "data-[position=ne]:cursor-nesw-resize data-[position=sw]:cursor-nesw-resize",
        "data-[position=nw]:cursor-nwse-resize data-[position=se]:cursor-nwse-resize",
        "data-disabled:cursor-default! data-loading:hidden",
        className,
      )}
      {...props}
    />
  );
}

function ImageCropperHandles({
  positions = imageCropperHandlePositions,
  className,
}: {
  positions?: readonly ImageCropperHandlePosition[];
  className?: string;
}) {
  return positions.map((position) => (
    <ImageCropperHandle
      key={position}
      position={position}
      className={className}
    />
  ));
}

function ImageCropperZoom({
  className,
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperZoomPrimitive>>) {
  return (
    <ImageCropperZoomPrimitive
      className={cn(
        "accent-primary h-1.5 w-full cursor-pointer disabled:cursor-not-allowed disabled:opacity-50",
        className,
      )}
      {...props}
    />
  );
}

function ImageCropperRotate({
  className,
  children,
  variant = "outline",
  size = "icon",
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperRotatePrimitive>> &
  ButtonStyleProps) {
  return (
    <ImageCropperRotatePrimitive
      render={<Button variant={variant} size={size} />}
      className={cn(className)}
      aria-label={children ? undefined : "Rotate"}
      {...props}
    >
      {children ?? <RotateCwIcon />}
    </ImageCropperRotatePrimitive>
  );
}

function ImageCropperFlip({
  className,
  children,
  direction = "horizontal",
  variant = "outline",
  size = "icon",
  ...props
}: WithClassName<React.ComponentProps<typeof ImageCropperFlipPrimitive>> &
  ButtonStyleProps) {
  return (
    <ImageCropperFlipPrimitive
      render={<Button variant={variant} size={size} />}
      direction={direction}
      className={cn(className)}
      aria-label={
        children
          ? undefined
          : direction === "vertical"
            ? "Flip vertically"
            : "Flip horizontally"
      }
      {...props}
    >
      {children ??
        (direction === "vertical" ? (
          <FlipVertical2Icon />
        ) : (
          <FlipHorizontal2Icon />
        ))}
    </ImageCropperFlipPrimitive>
  );
}

export {
  ImageCropper,
  ImageCropperViewport,
  ImageCropperImage,
  ImageCropperSelection,
  ImageCropperGrid,
  ImageCropperHandle,
  ImageCropperHandles,
  ImageCropperZoom,
  ImageCropperRotate,
  ImageCropperFlip,
  createImageCropperController,
  cropImage,
  imageCropperHandlePositions,
  type ImageCrop,
};
```

## Usage

```tsx
import {
  ImageCropper,
  ImageCropperGrid,
  ImageCropperHandles,
  ImageCropperImage,
  ImageCropperSelection,
  ImageCropperViewport,
} from "@/components/ui/image-cropper";
```

```tsx
<ImageCropper aria-label="Cover photo" src={src} onCropChange={setCrop}>
  <ImageCropperViewport>
    <ImageCropperImage alt="Mountain range" />
    <ImageCropperSelection>
      <ImageCropperGrid />
    </ImageCropperSelection>
    <ImageCropperHandles />
  </ImageCropperViewport>
</ImageCropper>
```

The crop is in the image's own pixels, not screen pixels. It looks like `{ x, y, width, height, rotation, flipX, flipY }` and can be passed straight to `cropImage`.

### Export the crop

```tsx
import { cropImage } from "@/components/ui/image-cropper";

const file = await cropImage(src, crop, {
  type: "image/webp",
  quality: 0.9,
  width: 800,
});
```

`cropImage` returns a `File`. Upload it, or show it with `URL.createObjectURL(file)` and revoke the URL when you are done. Remote images must allow CORS, which is why `ImageCropperImage` sets `crossOrigin="anonymous"`.

### Anatomy

| Part | Role |
| --- | --- |
| `ImageCropper` | Root. Holds the options and the crop state. Children can be a function of the state, for example `({ zoom }) => ...`. |
| `ImageCropperViewport` | The area the image shows in. Pans the image in frame mode and zooms with the mouse wheel. |
| `ImageCropperImage` | The image. Takes `alt` and the usual image props. |
| `ImageCropperSelection` | The crop area. Focusable, moved with the pointer or arrow keys. |
| `ImageCropperGrid` | Rule of thirds lines, shown while dragging. |
| `ImageCropperHandles` | The eight resize handles. Box mode only. |
| `ImageCropperZoom` | A native range input bound to the zoom level. |
| `ImageCropperRotate` | A button that turns the image a quarter clockwise. |
| `ImageCropperFlip` | A button that mirrors the image horizontally or vertically. |

## Examples

### Aspect Ratio

`aspectRatio` locks the selection to width over height, like `1`, `16 / 9` or `4 / 5`.

`image-cropper-aspect-ratio.tsx`:

```tsx
import {
  ImageCropper,
  ImageCropperGrid,
  ImageCropperHandles,
  ImageCropperImage,
  ImageCropperSelection,
  ImageCropperViewport,
} from "@/components/ui/image-cropper";

const photo =
  "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&q=80&auto=format&fit=crop";

export default function ImageCropperAspectRatio() {
  return (
    <ImageCropper
      aria-label="Photo"
      src={photo}
      aspectRatio={16 / 9}
      className="max-w-md"
    >
      <ImageCropperViewport>
        <ImageCropperImage alt="Mountain range above the clouds" />
        <ImageCropperSelection>
          <ImageCropperGrid />
        </ImageCropperSelection>
        <ImageCropperHandles />
      </ImageCropperViewport>
    </ImageCropper>
  );
}
```

### Frame Mode

`mode="frame"` keeps the selection still and pans and zooms the image under it.

`image-cropper-frame-mode.tsx`:

```tsx
import {
  ImageCropper,
  ImageCropperImage,
  ImageCropperSelection,
  ImageCropperViewport,
} from "@/components/ui/image-cropper";

const photo =
  "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&q=80&auto=format&fit=crop";

export default function ImageCropperFrameMode() {
  return (
    <ImageCropper
      aria-label="Photo"
      src={photo}
      mode="frame"
      aspectRatio={4 / 3}
      className="max-w-md"
    >
      <ImageCropperViewport>
        <ImageCropperImage alt="Mountain range above the clouds" />
        <ImageCropperSelection />
      </ImageCropperViewport>
    </ImageCropper>
  );
}
```

### Circle

`shape="circle"` rounds the selection. Pass `shape: "circle"` to `cropImage` as well, so the exported corners are transparent.

`image-cropper-circle.tsx`:

```tsx
import {
  ImageCropper,
  ImageCropperImage,
  ImageCropperSelection,
  ImageCropperViewport,
} from "@/components/ui/image-cropper";

const photo =
  "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&q=80&auto=format&fit=crop";

export default function ImageCropperCircle() {
  return (
    <ImageCropper
      aria-label="Photo"
      src={photo}
      mode="frame"
      shape="circle"
      aspectRatio={1}
      className="max-w-md"
    >
      <ImageCropperViewport>
        <ImageCropperImage alt="Mountain range above the clouds" />
        <ImageCropperSelection />
      </ImageCropperViewport>
    </ImageCropper>
  );
}
```

### Handles

`ImageCropperHandles` renders all eight handles by default. Pass `positions` to render only some of them.

`image-cropper-handles.tsx`:

```tsx
import {
  ImageCropper,
  ImageCropperHandles,
  ImageCropperImage,
  ImageCropperSelection,
  ImageCropperViewport,
} from "@/components/ui/image-cropper";

const photo =
  "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&q=80&auto=format&fit=crop";

export default function ImageCropperCornerHandles() {
  return (
    <ImageCropper
      aria-label="Photo"
      src={photo}
      aspectRatio={1}
      className="max-w-md"
    >
      <ImageCropperViewport>
        <ImageCropperImage alt="Mountain range above the clouds" />
        <ImageCropperSelection />
        <ImageCropperHandles positions={["nw", "ne", "se", "sw"]} />
      </ImageCropperViewport>
    </ImageCropper>
  );
}
```

### Controls

`ImageCropperZoom`, `ImageCropperRotate` and `ImageCropperFlip` connect to the cropper without extra state.

`image-cropper-controls.tsx`:

```tsx
import {
  ImageCropper,
  ImageCropperFlip,
  ImageCropperGrid,
  ImageCropperHandles,
  ImageCropperImage,
  ImageCropperRotate,
  ImageCropperSelection,
  ImageCropperViewport,
  ImageCropperZoom,
} from "@/components/ui/image-cropper";

const photo =
  "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&q=80&auto=format&fit=crop";

export default function ImageCropperControls() {
  return (
    <ImageCropper
      aria-label="Photo"
      src={photo}
      className="max-w-md"
    >
      <ImageCropperViewport>
        <ImageCropperImage alt="Mountain range above the clouds" />
        <ImageCropperSelection>
          <ImageCropperGrid />
        </ImageCropperSelection>
        <ImageCropperHandles />
      </ImageCropperViewport>
      <div className="flex items-center gap-2">
        <ImageCropperZoom aria-label="Zoom" />
        <ImageCropperRotate />
        <ImageCropperFlip />
        <ImageCropperFlip direction="vertical" />
      </div>
    </ImageCropper>
  );
}
```

### Disabled

`image-cropper-disabled.tsx`:

```tsx
import {
  ImageCropper,
  ImageCropperFlip,
  ImageCropperGrid,
  ImageCropperHandles,
  ImageCropperImage,
  ImageCropperRotate,
  ImageCropperSelection,
  ImageCropperViewport,
  ImageCropperZoom,
} from "@/components/ui/image-cropper";

const photo =
  "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=1200&q=80&auto=format&fit=crop";

export default function ImageCropperDisabled() {
  return (
    <ImageCropper
      aria-label="Photo"
      src={photo}
      disabled
      className="max-w-md"
    >
      <ImageCropperViewport>
        <ImageCropperImage alt="Mountain range above the clouds" />
        <ImageCropperSelection>
          <ImageCropperGrid />
        </ImageCropperSelection>
        <ImageCropperHandles />
      </ImageCropperViewport>
      <div className="flex items-center gap-2">
        <ImageCropperZoom aria-label="Zoom" />
        <ImageCropperRotate />
        <ImageCropperFlip />
        <ImageCropperFlip direction="vertical" />
      </div>
    </ImageCropper>
  );
}
```

Complete flows such as upload and crop, an avatar editor in a dialog and exporting to WebP are on the [Image Cropper components](https://shadcnuikit.com/components/image-cropper) page.

## API Reference

### ImageCropper

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `src` | `string` | | The image URL, like an object URL for a picked file. |
| `crop` | `ImageCrop` | | The crop, in image pixels. Pass it to control the cropper. |
| `defaultCrop` | `ImageCrop` | centered | The crop at first, when uncontrolled. Defaults to four fifths of the largest crop in box mode, the largest in frame mode. |
| `onCropChange` | `(crop, details) => void` | | Runs on every step of a drag, key or wheel, and once the image loads. |
| `onCropCommit` | `(crop, details) => void` | | Runs once an interaction ends: the pointer lifts, a key is pressed, the wheel pauses. Use it for saving. |
| `mode` | `"box"`, `"frame"` | `"box"` | `box` moves and resizes a selection over the image. `frame` keeps the selection still and pans the image, like an avatar editor. |
| `aspectRatio` | `number` | | Locks width over height, like `1` or `16 / 9`. Free when left out. |
| `shape` | `"rectangle"`, `"circle"` | `"rectangle"` | The selection shape. A circle is still a box to the crop. |
| `minWidth` | `number` | `1` | The narrowest the crop gets, in image pixels. |
| `minHeight` | `number` | `1` | The shortest the crop gets, in image pixels. |
| `maxZoom` | `number` | `10` | How far the crop magnifies, where 1 is the largest crop the image allows. |
| `disabled` | `boolean` | `false` | Stops every change. |
| `controller` | `ImageCropperController` | | Changes the crop from anywhere. Create one with `createImageCropperController()`. |
| `children` | `ReactNode` or `(state) => ReactNode` | | The parts. A function receives `crop`, `zoom`, `loading`, `error`, `dragging`, `mode`, `shape` and `disabled`. |

The root and its parts have `data-mode`, `data-shape`, `data-loading`, `data-dragging` and `data-disabled` attributes for styling.

### ImageCropperHandles

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `positions` | `ImageCropperHandlePosition[]` | all eight | Which handles to render: `nw`, `n`, `ne`, `e`, `se`, `s`, `sw`, `w`. |
| `className` | `string` | | Classes for every handle. |

Use `ImageCropperHandle` with a `position` prop to render a single handle.

### ImageCropperRotate and ImageCropperFlip

Both render a shadcn/ui `Button` and accept its `variant` and `size` props. The defaults are `variant="outline"` and `size="icon"`, with a Lucide icon and an English `aria-label`. Pass children to replace the icon.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `direction` | `"horizontal"`, `"vertical"` | `"horizontal"` | `ImageCropperFlip` only. Which way to mirror the image. |

### createImageCropperController

```tsx
const [controller] = React.useState(() => createImageCropperController());

<ImageCropper controller={controller} src={src}>...</ImageCropper>;

controller.getCrop(); // the crop, or null until the image loads
controller.setCrop({ x: 0, y: 0, width: 400, height: 400 });
controller.getZoom();
controller.setZoom(2);
controller.rotate(); // clockwise, or rotate(-1)
controller.flip("vertical");
controller.focus();
```

### cropImage

`cropImage(source, crop, options)` returns a `Promise<File>`. The source can be a `Blob`, a URL, an image element, a canvas or an `ImageBitmap`.

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `type` | `string` | `"image/png"` | The file type. Browsers that can't write it fall back to PNG. |
| `quality` | `number` | | From 0 to 1, for JPEG and WebP. |
| `width` | `number` | crop width | Output width. The height follows the crop ratio when left out. |
| `height` | `number` | crop height | Output height. The width follows the crop ratio when left out. |
| `shape` | `"rectangle"`, `"circle"` | `"rectangle"` | `circle` leaves the corners transparent in PNG and WebP. |
| `name` | `string` | | The file name. Defaults to the source name with the new extension. |

## Keyboard

The selection and every handle are focusable sliders.

| Key | Action |
| --- | --- |
| `Tab` | Moves focus to the selection, then to each handle. |
| `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight` | Moves the selection. On a handle, moves that edge. In frame mode, pans the image. |
| `Shift` + arrows | Moves ten times further. |
| `+`, `=` | Zooms in. |
| `-` | Zooms out. |
| `R` | Turns the image a quarter clockwise. |
| `Shift` + `R` | Turns the image a quarter counterclockwise. |

## Accessibility

- The selection is announced as a "crop area" slider and each handle as a "resize handle" named by its position, for example "Top left corner".
- Give the root an accessible name with `aria-label`, and the image a meaningful `alt`.
- The rotate and flip buttons have English labels by default. Pass `aria-label` to translate them.
- Disabled croppers remove the selection and handles from the tab order.

## For AI Agents

**When to use**

- Avatar and profile photo editors, with `mode="frame"` and `shape="circle"`.
- Cover images, banners and product photos that must match a fixed ratio.
- Any upload flow where the user should choose the visible part of an image before it is saved.

**When not to use**

- Only picking or uploading files, without cropping. Use a [File Upload](https://shadcnuikit.com/components/file-upload) component.
- Showing an image at a fixed ratio with no user input. Use CSS `aspect-ratio` with `object-fit: cover`.
- Comparing two images. Use [Comparison](https://shadcnuikit.com/components/comparison).

**Agent notes**

- Import from `@/components/ui/image-cropper`. `cropImage`, `createImageCropperController` and the `ImageCrop` type are exported from the same file.
- Crop values are in image pixels, after rotation and flips. Never convert them to screen pixels before calling `cropImage`.
- `onCropChange` fires on every drag step. Save to a server in `onCropCommit` instead.
- Remote images need CORS headers, or `cropImage` fails on a tainted canvas. Object URLs from file inputs always work.
- Revoke object URLs you create with `URL.revokeObjectURL` when the image changes or the component unmounts.
- For circular avatars, pass `shape: "circle"` to `cropImage` too. The cropper's shape only affects the selection.

**Resources**

- Markdown: [/docs/components/image-cropper.md](https://shadcnuikit.com/docs/components/image-cropper.md)
- Variants: [Image Cropper components](https://shadcnuikit.com/components/image-cropper), 10 free examples
- Install: `npx shadcn@latest add @shadcnuikit/image-cropper1`
- MCP: call `get_item_code` with `image-cropper1` from the [MCP Server](https://shadcnuikit.com/docs/mcp-server)
- Full index for agents: [llms.txt](https://shadcnuikit.com/llms.txt)

Source: https://shadcnuikit.com/docs/components/image-cropper
More from Shadcn UI Kit: [llms.txt](https://shadcnuikit.com/llms.txt)