View as Markdown

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.

Mountain range above the clouds

Installation

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. Image Cropper is free and installs without an API key.

Manual installation

Install the dependencies and the button component:

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
"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

import {
  ImageCropper,
  ImageCropperGrid,
  ImageCropperHandles,
  ImageCropperImage,
  ImageCropperSelection,
  ImageCropperViewport,
} from "@/components/ui/image-cropper";
<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

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

PartRole
ImageCropperRoot. Holds the options and the crop state. Children can be a function of the state, for example ({ zoom }) => ....
ImageCropperViewportThe area the image shows in. Pans the image in frame mode and zooms with the mouse wheel.
ImageCropperImageThe image. Takes alt and the usual image props.
ImageCropperSelectionThe crop area. Focusable, moved with the pointer or arrow keys.
ImageCropperGridRule of thirds lines, shown while dragging.
ImageCropperHandlesThe eight resize handles. Box mode only.
ImageCropperZoomA native range input bound to the zoom level.
ImageCropperRotateA button that turns the image a quarter clockwise.
ImageCropperFlipA 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.

Mountain range above the clouds

Frame Mode

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

Mountain range above the clouds

Circle

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

Mountain range above the clouds

Handles

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

Mountain range above the clouds

Controls

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

Mountain range above the clouds

Disabled

Mountain range above the clouds

Complete flows such as upload and crop, an avatar editor in a dialog and exporting to WebP are on the Image Cropper components page.

API Reference

ImageCropper

PropTypeDefaultDescription
srcstringThe image URL, like an object URL for a picked file.
cropImageCropThe crop, in image pixels. Pass it to control the cropper.
defaultCropImageCropcenteredThe crop at first, when uncontrolled. Defaults to four fifths of the largest crop in box mode, the largest in frame mode.
onCropChange(crop, details) => voidRuns on every step of a drag, key or wheel, and once the image loads.
onCropCommit(crop, details) => voidRuns 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.
aspectRationumberLocks 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.
minWidthnumber1The narrowest the crop gets, in image pixels.
minHeightnumber1The shortest the crop gets, in image pixels.
maxZoomnumber10How far the crop magnifies, where 1 is the largest crop the image allows.
disabledbooleanfalseStops every change.
controllerImageCropperControllerChanges the crop from anywhere. Create one with createImageCropperController().
childrenReactNode or (state) => ReactNodeThe 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

PropTypeDefaultDescription
positionsImageCropperHandlePosition[]all eightWhich handles to render: nw, n, ne, e, se, s, sw, w.
classNamestringClasses 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.

PropTypeDefaultDescription
direction"horizontal", "vertical""horizontal"ImageCropperFlip only. Which way to mirror the image.

createImageCropperController

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.

OptionTypeDefaultDescription
typestring"image/png"The file type. Browsers that can't write it fall back to PNG.
qualitynumberFrom 0 to 1, for JPEG and WebP.
widthnumbercrop widthOutput width. The height follows the crop ratio when left out.
heightnumbercrop heightOutput height. The width follows the crop ratio when left out.
shape"rectangle", "circle""rectangle"circle leaves the corners transparent in PNG and WebP.
namestringThe file name. Defaults to the source name with the new extension.

Keyboard

The selection and every handle are focusable sliders.

KeyAction
TabMoves focus to the selection, then to each handle.
ArrowUp, ArrowDown, ArrowLeft, ArrowRightMoves the selection. On a handle, moves that edge. In frame mode, pans the image.
Shift + arrowsMoves ten times further.
+, =Zooms in.
-Zooms out.
RTurns the image a quarter clockwise.
Shift + RTurns 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 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.

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