# Image Cropper

> React image cropper: drag to pan, wheel and pinch zoom, aspect presets, a round avatar mask and 90 degree rotation, returning the crop in source pixels.

- Kind: Component (Media)
- Docs: https://ui.minidev.pro/docs/image-cropper
- Source (registry JSON with the full file): https://ui.minidev.pro/r/image-cropper.json
- License: MIT. One file, yours to edit after install.

## When to use

Use it before uploading a cover, avatar or product photo. onCrop reports the crop in source pixels; getCroppedBlob(src, rect, opts) renders it to a Blob for upload. For picking a file without framing use ImageUpload, and for a round avatar picker use AvatarUpload. Keyboard: arrows pan (Shift for bigger steps), + and - zoom, R rotates, 0 resets.

## Installation

### shadcn CLI (copies the source into your project)

```bash
npx shadcn@latest add @minidev/image-cropper
```

Writes `components/ui/image-cropper.tsx` plus the MiniDev files it is built from (button, segmented-control, slider) and installs its npm dependencies. Older CLI versions: `npx shadcn@latest add https://ui.minidev.pro/r/image-cropper.json`.

### npm package

```bash
npm i minidev-ui-kit lucide-react motion
```

Add the tokens to your global stylesheet once:

```css
@import "tailwindcss";
@import "minidev-ui-kit/styles.css";
@source "../node_modules/minidev-ui-kit";
```

Next.js also needs `transpilePackages: ["minidev-ui-kit"]` in next.config.

## Import

After the shadcn install:

```tsx
import { ImageCropper, getCroppedBlob } from "@/components/ui/image-cropper"
```

From the npm package:

```tsx
import { ImageCropper } from "minidev-ui-kit/ui/image-cropper"
```

## Usage

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

export function Example() {
  return (
    <ImageCropper />
  )
}
```

## Props

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| `src` | `string` | `SAMPLE_SRC` | no | Image URL or data URI. Remote images need CORS headers for getCroppedBlob. |
| `alt` | `string` | `"Lumen sample landscape"` | no |  |
| `aspects` | `Aspect[]` | `["1:1", "4:3", "16:9"]` | no | Aspect presets offered, as "w:h". |
| `defaultAspect` | `Aspect` | `"4:3"` | no |  |
| `defaultCircle` | `boolean` | `false` | no | Start with the circular avatar mask on. |
| `allowCircle` | `boolean` | `true` | no | Offer the circular mask toggle. |
| `maxZoom` | `number` | `4` | no | Largest zoom, as a multiple of the size that just covers the frame. |
| `showPreview` | `boolean` | `true` | no | Show the live preview and crop details beside the frame. |
| `onCrop` | `(rect: CropRect, info: { aspect: Aspect; circle: boolean }) => void` | - | no | Called with the crop in source pixels once an interaction settles. |
| `fileName` | `string` | `"lumen-cover.png"` | no | File name used by the export button. |
| `className` | `string` | - | no |  |

## Examples

### Avatar crop

One square preset with the circle mask locked on, the usual setup for a profile photo picker.

```tsx
<ImageCropper
  aspects={["1:1"]}
  defaultAspect="1:1"
  defaultCircle
  allowCircle={false}
  alt="Maya Chen's profile photo"
  fileName="maya-chen-avatar.png"
/>
```

### Reading the crop

onCrop fires once an interaction settles with the rectangle in source pixels, ready to send to your server or to getCroppedBlob.

```tsx
function CoverDemo() {
  const [rect, setRect] = React.useState<CropRect | null>(null)
  const [saved, setSaved] = React.useState(false)
  return (
    <div className="flex w-full max-w-xl flex-col gap-3">
      <ImageCropper
        aspects={["16:9", "3:2"]}
        defaultAspect="16:9"
        allowCircle={false}
        showPreview={false}
        alt="Northwind launch cover"
        onCrop={(r) => {
          setRect(r)
          setSaved(false)
        }}
      />
      <div className="flex items-center justify-between gap-3 rounded-lg border border-border bg-surface px-3 py-2">
        <code className="truncate font-mono text-xs text-fg-muted">
          {rect ? `{ x: ${rect.x}, y: ${rect.y}, width: ${rect.width}, height: ${rect.height}, rotation: ${rect.rotation} }` : "Move the image to get a crop"}
        </code>
        <Button size="sm" disabled={!rect || saved} onClick={() => setSaved(true)}>
          {saved ? "Saved" : "Use as cover"}
        </Button>
      </div>
    </div>
  )
}
```

## Keyboard interactions

| Key | Action |
| --- | --- |
| `ArrowLeft` or `ArrowRight` or `ArrowUp` or `ArrowDown` | On the crop area, moves the image 12px. Hold Shift for 48px. |
| `Plus` or `=` | On the crop area, zooms in. |
| `-` or `_` | On the crop area, zooms out. |
| `R` | On the crop area, rotates 90 degrees clockwise. |
| `0` | On the crop area, resets position, zoom and rotation. |
| `ArrowLeft` or `ArrowRight` or `Home` or `End` | In the aspect ratio control, moves the selection between presets. |

## Accessibility

- The crop area is a focusable `role="group"` with `aria-roledescription="image cropper"` and `aria-label="Crop {alt}"`. Its `aria-describedby` points at hidden instructions listing the drag, arrow, zoom, R and 0 controls.
- The aspect presets are a `role="radiogroup"` with one Tab stop. The circle toggle has `aria-pressed`, and the rotate and zoom buttons have labels.
- Load and export failures render in `role="alert"` so they are announced. The preview image is named "Cropped preview of {alt}".
- Under reduced motion every spring has `duration: 0`, so pans, zooms and the circle mask change instantly.

## FAQ

### How do I upload the cropped image?

Keep the rectangle from `onCrop`, which fires about 160ms after an interaction settles. Then render it: `const blob = await getCroppedBlob(src, rect, { type: "image/webp", width: 800 })` and append the blob to `FormData`. Pass `circle: true` for a round avatar with transparent corners.

### Why does export fail for images on another domain?

Drawing a cross-origin image taints the canvas unless the server sends CORS headers. The cropper sets `crossOrigin="anonymous"` for remote URLs, so the server must answer with `Access-Control-Allow-Origin`. For a file the user picked, pass `URL.createObjectURL(file)`, which always works.

### How do I lock it to a square avatar crop?

Pass `aspects={["1:1"]}`, `defaultAspect="1:1"` and `defaultCircle`. Turning the circle on forces 1:1 and disables the other aspects. Set `allowCircle={false}` to hide the toggle.

### Are the crop numbers in screen pixels?

No. `x`, `y`, `width` and `height` are in source image pixels, measured after `rotation` (0, 90, 180 or 270), so they stay correct whatever size the frame is shown at.

## Rules for generating code

- Use semantic tokens only (bg, surface, sunken, border, fg, fg-muted, fg-subtle, ink, accent, success, warning, danger). Never raw hex or palette steps like blue-500.
- Shadows only from the set: shadow-xs, shadow-sm, shadow-raised, shadow-md, shadow-lg, shadow-overlay.
- Numbers use tabular-nums. Dark mode is the `dark` class on <html>; components never branch on theme.

## Dependencies

- npm: `lucide-react`, `motion`
- Built from: [button](https://ui.minidev.pro/docs/button/md), [segmented-control](https://ui.minidev.pro/docs/segmented-control/md), [slider](https://ui.minidev.pro/docs/slider/md)

## Related

- [Image Upload](https://ui.minidev.pro/docs/image-upload/md): A single image picker that starts as a drag and drop zone, then swaps to a large preview with a remove button. Returns an object URL and the File in React.
- [Avatar Upload](https://ui.minidev.pro/docs/avatar-upload/md): React profile photo uploader with an avatar preview and an Upload button that opens a hidden image file input. Shows initials until a picture is chosen.
- [File Dropzone](https://ui.minidev.pro/docs/file-dropzone/md): A React drag and drop upload zone with accept and reject states, type and size checks, image previews, per file progress, retry and screen reader updates.
- [Audio Player](https://ui.minidev.pro/docs/audio-player/md): Minimal React audio player row with a play and pause toggle, title, subtitle and an accessible progress bar. Controlled, so it works with any audio source.
- [Avatar](https://ui.minidev.pro/docs/avatar/md): Shadcn compatible avatar on Base UI with image and initials fallback, three sizes, a status badge and an overlapping avatar group with a plus count.
- [Carousel](https://ui.minidev.pro/docs/carousel/md): Scroll snap React carousel with previous and next buttons, arrow key support and a labelled region. Shows one, two or three slides by breakpoint, no library.

---

All 557 components: https://ui.minidev.pro/llms.txt (full text: https://ui.minidev.pro/llms-full.txt).
