# ImageCropper
Package: @mantine/core
Import: import { ImageCropper } from '@mantine/core';
Description: 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:

```tsx
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:

```tsx
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:

```tsx
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](https://alpha.mantine.dev/llms/guides-controllers.md) with the `useImageCropper` hook.

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

```tsx
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:

```tsx
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`:

```tsx
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:

```tsx
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>
  );
}
```


```tsx
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:

```tsx
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:

```tsx
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:

```tsx
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](https://alpha.mantine.dev/llms/x-dropzone.md) to pick an image, then pass its object URL to `ImageCropper`:

```tsx
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:

```tsx
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>
  );
}
```


#### Props

**ImageCropper props**

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| aspectRatio | number | - | Crop aspect ratio, e.g. `1` or `16 / 9`. Defaults to the viewport aspect ratio when not set |
| children | React.ReactNode | - | Custom layout built with `ImageCropper.Viewport`, `ImageCropper.Image` and `ImageCropper.Controls` |
| controller | ImageCropperController | - | Controller returned by the `useImageCropper` hook. When provided, the option props below are ignored |
| cropShape | ImageCropperCropShape | - | Crop shape, `'rectangle'` by default. `'circle'` enforces a square aspect ratio |
| crossOrigin | CrossOrigin | - | `crossorigin` attribute of the underlying image, set to `'anonymous'` to allow exporting CORS-enabled remote images |
| defaultFlip | ImageCropperFlip | - | Uncontrolled flip initial value |
| defaultRotation | number | - | Uncontrolled rotation initial value in degrees, `0` by default |
| defaultZoom | number | - | Uncontrolled zoom initial value, `1` by default |
| disabled | boolean | - | If set, the cropper is static and non-interactive, `false` by default |
| flip | ImageCropperFlip | - | Controlled flip value |
| maxZoom | number | - | Maximum zoom value, `5` by default |
| minZoom | number | - | Minimum zoom value, `1` by default |
| onCropChange | (data: ImageCropperCropData) => void | - | Called with `{ pixels, percent }` crop data whenever the crop rectangle changes, including during panning |
| onFlipChange | (flip: ResolvedImageCropperFlip) => void | - | Called when flip changes |
| onRotationChange | (rotation: number) => void | - | Called when rotation changes |
| onZoomChange | (zoom: number) => void | - | Called when zoom changes |
| rotation | number | - | Controlled rotation value in degrees |
| src | string | - | Image source, can be an object URL, data URL or remote URL |
| withControls | boolean | - | If set, default zoom, rotation and flip controls are rendered under the viewport, `false` by default |
| withGrid | boolean | - | If set, a rule-of-thirds grid is displayed over the crop area, `false` by default |
| zoom | number | - | Controlled zoom value |
| zoomStep | number | - | Zoom step used by wheel and default controls, `0.1` by default |


#### Styles API

ImageCropper component supports Styles API. With Styles API, you can customize styles of any inner element. Follow the documentation to learn how to use CSS modules, CSS variables and inline styles to get full control over component styles.

**ImageCropper selectors**

| Selector | Static selector | Description |
|----------|----------------|-------------|
| root | .mantine-ImageCropper-root | Root element |
| grid | .mantine-ImageCropper-grid | Rule-of-thirds grid container, rendered only when withGrid prop is set |
| gridLine | .mantine-ImageCropper-gridLine | Single rule-of-thirds grid line |
| zoomSlider | .mantine-ImageCropper-zoomSlider | Zoom slider in the default controls |

**ImageCropper data attributes**

| Selector | Attribute | Condition | Value |
|----------|-----------|-----------|-------|
| viewport | data-active | The image is being panned | - |
