react-modern-image-cropper
v0.2.2
Published
Modern React image cropper with AI auto-crop, rotation, filters, adjustments, mobile gestures & premium glassmorphic UI
Maintainers
Readme
react-modern-image-cropper
Modern, feature-rich React image cropper with a ready-made crop dialog, live previews, face-aware auto-crop, size-targeted compression, mobile gestures and editing tools.
✨ Features
| | |
|---|---|
| 🎯 Interactive cropping | Drag to move, 8 resize handles, rule-of-thirds grid |
| ⭕ Rectangle & circle | Round / circular crop with a true circular export mask |
| 🤖 AI Auto-Crop | Face-aware framing via MediaPipe (graceful offline fallback) |
| ⚡ Smart compression | Target a file size in KB — quality is auto-tuned via binary search |
| 🔄 Rotation & flip | Straighten slider, 90° rotate, horizontal/vertical flip |
| 🎨 10 filter presets | Vivid, Noir, Vintage, Chrome, Dramatic, Fade… |
| 🎚️ Pro adjustments | Brightness, contrast, saturation + exposure, highlights, shadows, temperature, hue, sharpness, blur |
| 📐 Aspect ratios | Presets, custom W:H input, and a lock toggle |
| 📱 Mobile gestures | Pinch-to-zoom and two-finger rotate |
| 📋 Clipboard paste | Paste an image straight from the clipboard (⌘/Ctrl+V) |
| ⌨️ Keyboard shortcuts | Nudge, rotate, flip, zoom, undo/redo |
| ↩️ Undo / redo | Full edit history |
| 💾 Export | PNG / JPEG / WebP with a live preview modal & savings readout |
| 🌗 Themes | Light / dark, fully TypeScript typed, headless-friendly |
📚 Detailed docs: API Reference · Styling Guide · Examples · ⚡ Live Playground
📦 Installation
npm install react-modern-image-cropper
# or
yarn add react-modern-image-cropper
# or
pnpm add react-modern-image-cropperreact and react-dom (v18 or v19) are peer dependencies — you almost
certainly already have them.
Import the styles once
The component ships a single prebuilt stylesheet. Import it in your app entry
(e.g. main.tsx, App.tsx, or _app.tsx):
import 'react-modern-image-cropper/styles.css'The stylesheet is self-contained (compiled Tailwind) — you do not need Tailwind installed in your own project to use the component. Every rule is scoped to the editor's own
.rmic-rootwrapper, so it never restyles your app's headings, buttons, images or fonts. If you forget this import, the editor logs a console warning.
🚀 Quick start
import { Cropper } from 'react-modern-image-cropper'
import 'react-modern-image-cropper/styles.css'
export default function App() {
return (
<div style={{ height: 640 }}>
<Cropper
src="https://example.com/photo.jpg"
aspectRatio={16 / 9}
defaultTheme="dark"
onCrop={(result) => {
console.log(result.dataUrl) // base64 string
console.log(result.blob) // Blob, ready to upload
console.log(result.width, result.height)
}}
/>
</div>
)
}That's it — drop the component in a sized container and you get the full editor: upload/drag/paste an image, crop, adjust, filter, and export.
⚙️ <Cropper /> props
| Prop | Type | Default | Description |
| -------------------- | ----------------------------------- | --------- | ----------------------------------------------------------------- |
| src | string \| File \| Blob | — | Image URL, data URL, or a File straight from <input type="file">. Omit to show the upload drop-zone. Remote URLs on another domain need CORS headers. |
| aspectRatio | number \| null | null | width / height (e.g. 1 for square product shots). Applied as soon as the image loads and kept by Reset. |
| showAspectRatios | boolean | true | Hide the aspect presets so users can't leave your required ratio. |
| shape | 'rect' \| 'round' | 'rect' | Initial crop shape. 'round' produces a circular export. |
| defaultTheme | 'light' \| 'dark' | 'dark' | Starting theme. |
| disableAutoCrop | boolean | false | Hide the AI button and skip the MediaPipe model download. |
| enablePaste | boolean | true | Allow loading an image by pasting (⌘/Ctrl+V). |
| defaultCompression | CompressionOptions | — | Pre-fill the export dialog's compression controls. |
| onCrop | (result: CropResult) => void | — | Fired when the user confirms the export dialog. When set, no file is downloaded — upload result.file yourself. |
| downloadOnExport | boolean | !onCrop | Also save the file to the user's device. |
| exportLabel | string | 'Export'| Label of the export button. |
| confirmLabel | string | 'Download' / 'Apply' | Label of the export dialog's confirm button. |
| onImageLoad | (image: HTMLImageElement) => void | — | Fired whenever a new image is loaded. |
| onError | (error: Error) => void | — | Fired when an image fails to load (bad URL, CORS, wrong file type). The error is also shown in the editor. |
| accept | string | 'image/*,video/*' | File types for the picker / drop-zone, e.g. 'image/*'. |
| title | ReactNode | 'Modern Image Cropper' | Header title; null hides it. |
| className | string | — | Extra class on the outer wrapper. |
| showCropTab | boolean | true | Show the Crop tab in the toolbar. |
| showAdjustTab | boolean | true | Show the Light adjustments tab. |
| showColorTab | boolean | true | Show the Color adjustments tab. |
| showFiltersTab | boolean | true | Show the Filters tab. |
| showUndoRedo | boolean | true | Show the Undo/Redo buttons in the header. |
| showReset | boolean | true | Show the Reset button in the header. |
| showThemeToggle | boolean | true | Show the Theme Toggle button in the header. |
| onlyIcons | boolean | false | Hide tab labels in the bottom bar and only show icons to save space.|
| customStyles | object | — | Custom CSS classes: { headerButton?, tabButton?, actionButton?, exportButton? }.|
The CropResult you receive
interface CropResult {
dataUrl: string // "data:image/...;base64,..."
blob: Blob // ready to POST as multipart/form-data
file: File // same image as a named File: formData.append('image', result.file)
width: number
height: number
format: 'image/png' | 'image/jpeg' | 'image/webp'
pixelCrop: { x, y, width, height } // crop rect on the source image
compression?: { // present when smart compression ran
originalBytes: number
compressedBytes: number
savings: number // 0..1
quality: number // final quality the search settled on
passes: number
}
}⚡ Smart compression
Two ways to use it.
1. In the export dialog — toggle Smart compression, set a target size, and the component finds the highest quality that fits. Or pre-configure it:
<Cropper
src={url}
defaultCompression={{ enabled: true, maxSizeKB: 200, maxDimension: 1600 }}
onCrop={(r) => console.log(`Saved ${Math.round(r.compression!.savings * 100)}%`)}
/>2. Headless — compress any File / Blob / URL without the UI:
import { useImageCompression } from 'react-modern-image-cropper'
function Uploader() {
const { compress, compressing } = useImageCompression()
const onFile = async (file: File) => {
const { blob, stats } = await compress(file, {
maxSizeKB: 300, // target ≤ 300 KB
maxDimension: 1920, // downscale longest edge to ≤ 1920px
format: 'image/webp',
})
await uploadToServer(blob)
console.log(`${(stats.savings * 100).toFixed(0)}% smaller in ${stats.passes} passes`)
}
// ...
}Or call the pure utility directly — compressImage(source, options).
How it works: the image is optionally downscaled, then the encoder runs a bounded binary search (~7 passes) over the JPEG/WebP quality range to find the best quality under your byte budget. PNG can't be quality-compressed, so when you set a hard size target on a PNG it's transparently re-encoded as WebP.
⌨️ Keyboard shortcuts
| Key | Action |
| -------------- | ---------------------------- |
| Arrow keys | Nudge crop (Shift = larger) |
| [ / ] | Rotate −/+ 1° |
| R | Rotate 90° |
| H / V | Flip horizontal / vertical |
| + / - | Zoom in / out |
| 0 | Reset all edits |
| ⌘/Ctrl + Z | Undo |
| ⌘/Ctrl + ⇧ Z | Redo |
| ⌘/Ctrl + V | Paste image from clipboard |
📦 Bulk Compressor Component
react-modern-image-cropper features a powerful <BulkCompressor /> component for batch cropping, adjustment filtering, and size-targeted smart compression (supporting files of any size, from KB to multiple MBs, and compressing them to a precise target).
Key Features
- Visual Batch Studio: Renders an interactive editor stage that lets the user visually adjust the crop frame, aspect ratio, shape, filters, and adjustments on the active image.
- Master Synchronization: Adjusting the crop box framing or color settings on the active image automatically applies the same relative layout and tone adjustments to all images in the queue when processing.
- Horizontal Thumbnail Slider: Displays a scrollable list of uploaded image thumbnails. Users can click any image to load it as the active preview and delete individual items.
- Any Target Size (KB & MB): Accepts arbitrary size targets in both KB and MB (e.g.
200 KB,1.5 MB), handling original images of all sizes (e.g., 1.3 MB, 8 MB, 476 KB). - Slider Toggle: The thumbnail slider can be hidden/shown via a UI checkbox or the
showImageSliderprop.
import { BulkCompressor } from 'react-modern-image-cropper'
import 'react-modern-image-cropper/styles.css'
function MyComponent() {
return <BulkCompressor showImageSlider={true} />
}<BulkCompressor /> Props
| Prop | Type | Default | Description |
|---|---|---|---|
| showImageSlider | boolean | true | Show/hide the horizontal thumbnail slider at the bottom. |
Free vs. Premium Batch Limits
The component has built-in tier tracking (stored in localStorage):
| Limits | Free Tier | Premium Tier | | :--- | :--- | :--- | | Max images per batch | 10 images | 100 images | | Daily batch runs | 4 batches | Unlimited | | Upgrade Option | Opens upgrade modal (fully theme-adaptive) | Built-in badge |
Note: All compression parameters (preset settings, target size, output shape, filters, adjustments, etc.) are exactly the same for both Free and Premium tiers. The only differences are the batch queue size and daily batch limits.
🧩 Headless / composable usage
Every building block is exported, and all editor state lives in a single Zustand store — so you can build a fully custom UI on top of the same engine.
import {
CropArea,
FilterPresets,
AdjustmentSliders,
useCropStore,
useCropState,
renderCrop,
} from 'react-modern-image-cropper'
function MyEditor() {
const { exportCrop } = useCropState()
const rotation = useCropStore((s) => s.rotation)
// compose your own layout around <CropArea />, the slider panels, etc.
}See the API Reference for the full export list (components, hooks, store actions, and utilities).
📦 Bundle Size & Optimization
Although react-modern-image-cropper is packed with professional features, it is built to keep your initial page loads fast:
- Lazy-loaded AI Auto-Crop: The heavy MediaPipe model and tasks-vision libraries are dynamically imported only when the user clicks the "AI Auto-Crop" button. If not used, they add zero weight to your bundle.
- Tree-shaken dependencies: Standard packages like Lucide Icons and Framer Motion are fully tree-shaken, ensuring you only bundle the modules actually rendered.
- Zero Tailwind Overhead: The component pre-compiles styles into a standalone sheet. You do not need to install or run Tailwind in your host application.
🎨 Styling & theming
The component is themed with CSS and a small set of accent variables — you can restyle it without forking. Full details in the Styling Guide:
- Toggle light/dark via the
defaultThemeprop oruseCropStore().setTheme(). - Override the accent gradient with CSS custom properties.
- Pass
classNameto size/position the wrapper. - Tailwind users can
@sourcethe package to extend it.
🌐 Next.js & SSR Integration Guide
Because react-modern-image-cropper relies on HTML5 Canvas APIs, standard mouse/touch window events, and browser-side MediaPipe decoders, it must run on the client side only.
If you import the component directly into an SSR page in Next.js, you will encounter a window is not defined or HTMLCanvasElement is not defined error. Here is how to load it safely using Next.js App Router and Pages Router:
1. App Router (Next.js 13+)
Create a client wrapper for the cropper (e.g., components/CropperWrapper.tsx):
'use client'
import { Cropper } from 'react-modern-image-cropper'
import 'react-modern-image-cropper/styles.css'
export default function CropperWrapper(props: React.ComponentProps<typeof Cropper>) {
return <Cropper {...props} />
}Then load it dynamically in your page with SSR disabled:
import dynamic from 'next/dynamic'
const DynamicCropper = dynamic(() => import('@/components/CropperWrapper'), {
ssr: false,
loading: () => (
<div className="h-[500px] flex items-center justify-center bg-neutral-900 text-white/50 rounded-3xl">
Loading editor...
</div>
),
})
export default function EditProfilePage() {
return (
<main className="max-w-2xl mx-auto p-8">
<h1 className="text-2xl font-bold mb-4">Edit Profile Picture</h1>
<div className="h-[600px] rounded-3xl overflow-hidden border border-neutral-800">
<DynamicCropper
aspectRatio={1}
onCrop={(res) => console.log('Cropped blob:', res.blob)}
/>
</div>
</main>
)
}2. Pages Router
Use next/dynamic to load the editor directly:
import dynamic from 'next/dynamic'
const Cropper = dynamic(
() => import('react-modern-image-cropper').then((mod) => mod.Cropper),
{ ssr: false }
)
export default function MyPage() {
return (
<div style={{ height: 600 }}>
<Cropper onCrop={(r) => console.log(r)} />
</div>
)
}<CropperModal />: crop dialog
A dialog with the crop area on the left, live previews on the right, a zoom slider and Save / Cancel. Built for the usual upload flows: avatars, product photos, cover images.
import { CropperModal } from 'react-modern-image-cropper'
import 'react-modern-image-cropper/styles.css'
export function ChangeAvatar() {
return (
<CropperModal
trigger={<button>Change photo</button>}
shape="round"
output={{ width: 256 }}
onCrop={async ({ file }) => {
const body = new FormData()
body.append('avatar', file)
await fetch('/api/avatar', { method: 'POST', body })
}}
/>
)
}Without src the dialog opens with a drop zone (paste works too). A <button>
trigger never submits a surrounding <form>. Escape and the backdrop close it,
focus stays inside while it's open, and it goes full screen on phones.
Open it from a file input
const [file, setFile] = useState<File | null>(null)
<input type="file" accept="image/*" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
<CropperModal
open={!!file}
onOpenChange={(open) => !open && setFile(null)}
src={file ?? undefined}
aspectRatio={1}
onCrop={(result) => upload(result.file)}
/>Props
| Prop | Type | Default | Description |
|---|---|---|---|
| src | string \| File \| Blob | — | Image to edit. Omit to show a drop zone. |
| trigger | ReactNode | — | Element that opens the dialog when clicked. |
| open / onOpenChange | boolean / (open) => void | — | Control the dialog yourself. |
| onCrop | (result: CropResult) => void | — | Called on Save with file, blob, dataUrl, width, height. |
| title | ReactNode | 'Edit image' | Dialog title. |
| shape | 'rect' \| 'round' | 'rect' | Circle crops are always 1:1. |
| aspectRatio | number \| null | null | Fixed ratio, e.g. 16 / 9. |
| previewSizes | number[] | [128, 64] | Live preview sizes (longest side, px). [] hides the preview column. |
| output | { format?, quality?, width?, height? } | see below | Format and size of the saved image. Give only width or height to keep the crop's ratio. |
| tools | CropperModalTools | see below | Turn individual tools off. |
| showExportDialog | boolean | false | On Save, let the user pick format and a max file size first. |
| defaultTheme | 'light' \| 'dark' \| 'system' | 'light' | Color scheme. |
| size | 'md' \| 'lg' \| 'fullscreen' | 'md' | Dialog size. Always full screen below 640px. |
| submitLabel / cancelLabel | string | 'Save' / 'Cancel' | Button labels. |
| closeOnCrop / closeOnEscape / closeOnBackdropClick | boolean | true | Closing behaviour. |
| downloadOnExport | boolean | false | Also save the file to the device. |
| defaultCompression | CompressionOptions | — | e.g. { enabled: true, maxSizeKB: 200 } to cap the file size. |
| accept | string | 'image/*' | File types for the drop zone. |
| onImageLoad / onError | | | Load and error callbacks. |
| container | HTMLElement | document.body | Where the dialog is portaled. |
| className | string | — | Extra classes for the dialog panel. |
Output defaults: PNG for circle crops (transparent corners), JPEG at 92%
otherwise, WebM for video. Native crop resolution unless width/height is set.
Tools (tools prop), all true unless noted:
interface CropperModalTools {
aspectRatios?: boolean // off by default when aspectRatio or shape="round" is set
shape?: boolean // off by default when the shape prop is set
rotate?: boolean
adjustments?: boolean
filters?: boolean
autoCrop?: boolean // face detection; loads MediaPipe on first use
zoom?: boolean
}Want the previews somewhere else? <CropPreview size={64} /> works inside any
<Cropper /> or <CropperProvider>.
🖼️ Framework notes
- Vite / Create React App: No special configuration required. Simply import
<Cropper />andstyles.cssdirectly. - Next.js App Router: the bundle is marked
'use client', so it can be imported from server components. - Images from another domain / CDN: the server must send
Access-Control-Allow-Origin, otherwise the browser blocks loading it into a canvas. The editor shows a clear error and callsonError.
⬆️ Upgrading from 0.1.x
New look. The UI is now a neutral, light-by-default design themed with CSS variables (
--rmic-accent,--rmic-radius, …). The old--rac-accent-from/via/togradient variables are gone; see docs/STYLING.md.defaultThemenow defaults to'light'(was'dark') and accepts'system'.<CropperModal />was redesigned: it saves directly with Save instead of going through the export dialog (opt back in withshowExportDialog), usestoolsinstead of the removed ⚙️ settings popover (defaultSettingsstill works), and is a centred dialog by default (size="fullscreen"replacesfitToScreen).<BulkCompressor />no longer has usage limits or an upgrade prompt.Each
<Cropper />now has its own state. Several croppers on a page no longer mirror each other, and reopening<CropperModal />for another image starts clean. If you read or drive the editor from a sibling component (useCropStore,useCropState), wrap both in<CropperProvider>:<CropperProvider> <Cropper src={src} /> <MyExportButton /> {/* uses useCropState() */} </CropperProvider>onCropno longer forces a download. PassdownloadOnExportto keep the old behaviour.<CropperModal closeOnCrop>now defaults totrue.Keyboard shortcuts and paste only apply while the editor has focus, so arrow keys, Ctrl+Z and pasting elsewhere on your page work normally.
Styles are scoped to
.rmic-rootand no longer include a global reset or the Inter web font import. Dark mode follows the cropper's ownrmic-darkclass, not your app's.dark.The CommonJS build is now
dist/index.umd.cjsand dependencies are no longer bundled into the library.
🛠️ Local development
npm install
npm run dev # playground app at http://localhost:5173
npm run build # build the library → dist/
npm run build:demo # build the playground app → dist-demo/
npm run preview # preview a production build📄 License
MIT © Ram — free for personal and commercial use.
