ImageCropper

Interactive image crop, zoom, rotate and flip with canvas export

Usage

ImageCropper lets users pan, zoom, rotate and flip an image behind a fixed crop window. Drag the image to pan and use the mouse wheel to zoom:

import { ImageCropper } from '@mantine/core';

const image = 'https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-9.png';

function Demo() {
  return (
    <ImageCropper
      src={image}
      crossOrigin="anonymous"
      maw={360}
      mx="auto"
      withControls
    />
  );
}

Interactions

  • Pan – drag the image or focus the viewport and use the arrow keys
  • Zoom – pinch with two fingers, scroll the mouse wheel or use the zoom slider. Press + or - to zoom when the viewport is focused. Set minZoom and maxZoom to limit zoom.
  • Rotate and flip – use the default controls or the controller actions

Set withControls to display the zoom slider and rotate, flip and reset buttons under the viewport.

Aspect ratio

Set aspectRatio to control the shape of the crop window, for example 1 for a square or 16 / 9 for a widescreen crop. When aspectRatio is not set, the crop window matches the viewport aspect ratio:

import { ImageCropper } from '@mantine/core';

const image = 'https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-9.png';

function Demo() {
  return (
    <ImageCropper
      src={image}
      crossOrigin="anonymous"
      aspectRatio={16 / 9}
      maw={480}
      mx="auto"
      withGrid
      withControls
    />
  );
}

Circle crop

Set cropShape="circle" to display a circular crop window, for example for avatars. The crop is always square and the exported image has a circular mask:

import { ImageCropper } from '@mantine/core';

const image = 'https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-9.png';

function Demo() {
  return (
    <ImageCropper
      src={image}
      crossOrigin="anonymous"
      cropShape="circle"
      maw={320}
      mx="auto"
      withControls
    />
  );
}

useImageCropper hook

ImageCropper supports the controller pattern with the useImageCropper hook.

When you pass a controller, set zoom, rotation, flip, crop shape and aspect ratio on the hook:

import { useImageCropper } from '@mantine/core';

function Demo() {
  const controller = useImageCropper({ cropShape: 'circle', maxZoom: 4 });

  controller.zoom; // -> number, current zoom
  controller.rotation; // -> number, current rotation in degrees
  controller.flip; // -> { horizontal: boolean, vertical: boolean }
  controller.crop; // -> { x, y }, pan offset in viewport pixels relative to the center
  controller.cropSize; // -> { width, height } of the crop window in viewport pixels, or null

  controller.setZoom(2); // clamped to minZoom/maxZoom
  controller.zoomBy(0.5);
  controller.setRotation(90);
  controller.rotateBy(-90);
  controller.flipHorizontal();
  controller.flipVertical();
  controller.setCrop({ x: 20, y: 0 }); // constrained to keep the crop window covered
  controller.reset(); // zoom, rotation, flip and pan back to their initial values

  controller.getCropData(); // -> ImageCropperArea in natural source pixels, or null
  controller.getCroppedImage({ type: 'image/png' }); // -> Promise<Blob | string>

  return null;
}

Example of using useImageCropper hook:

zoom: 1.0×, rotation: 0°, flipped: false

import { Button, Group, ImageCropper, Stack, Text, useImageCropper } from '@mantine/core';

const image = 'https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-9.png';

function Demo() {
  const controller = useImageCropper({ aspectRatio: 4 / 3, maxZoom: 4 });

  return (
    <Stack maw={420} mx="auto">
      <ImageCropper src={image} crossOrigin="anonymous" controller={controller} />

      <Group gap="xs" justify="center">
        <Button variant="default" size="xs" onClick={() => controller.zoomBy(-0.5)}>
          Zoom out
        </Button>
        <Button variant="default" size="xs" onClick={() => controller.zoomBy(0.5)}>
          Zoom in
        </Button>
        <Button variant="default" size="xs" onClick={() => controller.rotateBy(90)}>
          Rotate 90°
        </Button>
        <Button variant="default" size="xs" onClick={controller.flipHorizontal}>
          Flip
        </Button>
        <Button variant="default" size="xs" onClick={controller.reset}>
          Reset
        </Button>
      </Group>

      <Text size="sm" c="dimmed" ta="center">
        zoom: {controller.zoom.toFixed(1)}×, rotation: {controller.rotation}°, flipped:{' '}
        {String(controller.flip.horizontal)}
      </Text>
    </Stack>
  );
}

Controlled state

Zoom, rotation and flip can be controlled or uncontrolled with value, defaultValue and onChange style props, both on ImageCropper and in useImageCropper:

import { useState } from 'react';
import { ImageCropper } from '@mantine/core';

function Demo() {
  const [zoom, setZoom] = useState(1.5);
  const [rotation, setRotation] = useState(0);

  return (
    <ImageCropper
      src="/image.png"
      zoom={zoom}
      onZoomChange={setZoom}
      rotation={rotation}
      onRotationChange={setRotation}
      defaultFlip={{ horizontal: true }}
      withControls
    />
  );
}

The pan position cannot be controlled with props, set it with the controller setCrop action.

Exporting the crop

getCroppedImage returns a promise that resolves with the cropped image as a Blob or a data URL. Use type, quality and output options to change the result format:

Preview

import { useState } from 'react';
import { Button, Group, ImageCropper, Stack, Text, useImageCropper } from '@mantine/core';

const image = 'https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-9.png';

function Demo() {
  const controller = useImageCropper({ cropShape: 'circle' });
  const [preview, setPreview] = useState<string | null>(null);

  const handleExport = async () => {
    const dataUrl = (await controller.getCroppedImage({ output: 'dataURL' })) as string;
    setPreview(dataUrl);
  };

  return (
    <Group align="flex-start" justify="center">
      <Stack w={300}>
        <ImageCropper
          src={image}
          crossOrigin="anonymous"
          controller={controller}
          withControls
        />
        <Button onClick={handleExport}>Crop image</Button>
      </Stack>

      <Stack align="center" gap="xs">
        <Text size="sm" c="dimmed">Preview</Text>
        {preview ? (
          <img src={preview} alt="Cropped result" width={140} height={140} style={{ borderRadius: '50%' }} />
        ) : (
          <div
            style={{
              width: 140,
              height: 140,
              borderRadius: '50%',
              border: '1px dashed var(--mantine-color-gray-4)',
            }}
          />
        )}
      </Stack>
    </Group>
  );
}
const blob = await controller.getCroppedImage({ type: 'image/jpeg', quality: 0.9 });
const dataURL = await controller.getCroppedImage({ output: 'dataURL' });

To export a remote image, set crossOrigin="anonymous" on ImageCropper and make sure the image host sends permissive CORS headers, otherwise the promise is rejected. Object URLs and data URLs, for example from a file input, do not need extra configuration.

With cropShape="circle", the area outside the circle is transparent. Use image/png or image/webp type, with image/jpeg the corners are filled with an opaque color.

Server-side cropping

If you crop the image on the server, use getCropData() or the onCropChange callback instead of exporting the image on the client. Both provide the crop rectangle in pixels of the source image as { x, y, width, height, rotation }, onCropChange also receives it in percentages:

import { ImageCropper } from '@mantine/core';

function Demo() {
  return (
    <ImageCropper
      src="/image.png"
      onCropChange={({ pixels, percent }) => console.log(pixels, percent)}
    />
  );
}

The rectangle is measured in the rotated image. Flip is not part of the crop data, get it from controller.flip or onFlipChange. To reproduce the crop on the server:

  1. Apply the flip to the source image.
  2. Rotate the flipped image by pixels.rotation degrees, expanding the canvas to the rotated bounding box.
  3. Extract the pixels rectangle from the result.

Custom layout

Use ImageCropper.Viewport, ImageCropper.Image and ImageCropper.Controls compound components to change the layout, for example to render the controls above the viewport. Pass children to ImageCropper.Controls to replace the default controls:

import { ImageCropper, Stack } from '@mantine/core';

const image = 'https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-9.png';

function Demo() {
  return (
    <ImageCropper src={image} crossOrigin="anonymous" aspectRatio={1} withGrid maw={320} mx="auto">
      <Stack gap="xs">
        <ImageCropper.Controls />
        <ImageCropper.Viewport>
          <ImageCropper.Image />
        </ImageCropper.Viewport>
      </Stack>
    </ImageCropper>
  );
}

Disabled state

Set disabled to make the cropper non-interactive, for example to display a preview of a saved crop. The default controls are disabled as well:

import { ImageCropper } from '@mantine/core';

const image = 'https://raw.githubusercontent.com/mantinedev/mantine/master/.demo/images/bg-9.png';

function Demo() {
  return <ImageCropper src={image} maw={360} mx="auto" withControls disabled />;
}

Pairing with Dropzone

Use Dropzone to pick an image, then pass its object URL to ImageCropper:

Drop an image here or click to select one

import { useEffect, useState } from 'react';
import { ImageCropper, Stack, Text } from '@mantine/core';
import { Dropzone, IMAGE_MIME_TYPE } from '@mantine/dropzone';

function Demo() {
  const [src, setSrc] = useState<string>();

  useEffect(() => () => {
    if (src) {
      URL.revokeObjectURL(src);
    }
  }, [src]);

  return (
    <Stack maw={360} mx="auto">
      <Dropzone
        accept={IMAGE_MIME_TYPE}
        multiple={false}
        onDrop={([file]) => setSrc(URL.createObjectURL(file))}
      >
        <Text ta="center">Drop an image here or click to select one</Text>
      </Dropzone>
      {src && <ImageCropper src={src} aspectRatio={1} withControls />}
    </Stack>
  );
}

Accessibility

Set aria-label on ImageCropper.Viewport to describe what the user is cropping. To localize the controls, render buttons with translated labels:

import { Button, ImageCropper, useImageCropper } from '@mantine/core';

function Demo() {
  const controller = useImageCropper();

  return (
    <ImageCropper src="/avatar.jpg" controller={controller}>
      <ImageCropper.Viewport aria-label="Recadrer la photo de profil">
        <ImageCropper.Image />
      </ImageCropper.Viewport>
      <ImageCropper.Controls>
        <Button onClick={() => controller.rotateBy(90)}>Pivoter</Button>
        <Button onClick={controller.reset}>Réinitialiser</Button>
      </ImageCropper.Controls>
    </ImageCropper>
  );
}