# Image cropper

Frames one picked image to the shape a surface needs: pan, zoom, rotate, an aspect preset, and the output as a file.

- Family: form
- Import: `import { ImageCropper } from "@senvenli/react/form";`
- Page: https://design.senvenli.com/docs/components/image-cropper
- JSON: https://design.senvenli.com/docs/components/image-cropper.json

## Example: Crop to a cover photo

Pan, zoom and rotate inside a 16:9 frame; saving hands back a file.

```tsx
import { Text } from "@senvenli/react/display";
import { ImageCropper } from "@senvenli/react/form";
import { Stack } from "@senvenli/react/layout";
import { useState } from "react";

// A flat placeholder photo drawn in the file, so the example needs no network.
const PHOTO = `data:image/svg+xml,${encodeURIComponent(
  `<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1200"><rect width="1600" height="1200" fill="hsl(210 30% 62%)"/><circle cx="800" cy="600" r="320" fill="hsl(210 30% 46%)"/><text x="800" y="600" fill="hsl(210 30% 20%)" font-family="system-ui" font-size="72" text-anchor="middle" dominant-baseline="middle">Storefront</text></svg>`,
)}`;

export default function Example() {
  const [saved, setSaved] = useState<string>();
  return (
    <div className="max-w-xl">
      <Stack space="space-150">
        <ImageCropper
          src={PHOTO}
          label="Cover photo"
          fileName="cover"
          onCrop={(file, result) => setSaved(`${file.name}, ${result.width} × ${result.height} px`)}
        />
        {saved && <Text tone="subtle">Saved {saved}</Text>}
      </Stack>
    </div>
  );
}
```

## Examples

### Aspect presets

When one image feeds several surfaces, people choose the shape first.

```tsx
import { Text } from "@senvenli/react/display";
import { ImageCropper } from "@senvenli/react/form";
import { Stack } from "@senvenli/react/layout";
import { useState } from "react";

// A flat placeholder logo drawn in the file, so the example needs no network.
const LOGO = `data:image/svg+xml,${encodeURIComponent(
  `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800"><rect width="1200" height="800" fill="hsl(150 30% 90%)"/><path d="M400 600 600 200l200 400Z" fill="hsl(150 30% 30%)"/></svg>`,
)}`;

const PRESETS = [
  { id: "cover", label: "Cover 16:9", aspectRatio: 16 / 9 },
  { id: "square", label: "Square", aspectRatio: 1 },
  // A logo must stay whole: this surface fits the image instead of filling the frame.
  { id: "logo", label: "Logo 3:1", aspectRatio: 3, fit: "contain" },
] as const;

export default function Example() {
  const [saved, setSaved] = useState<string>();
  return (
    <div className="max-w-xl">
      <Stack space="space-150">
        <ImageCropper
          src={LOGO}
          label="Company logo"
          aspectPresets={PRESETS}
          outputType="image/png"
          fileName="logo"
          onCrop={(file, result) => setSaved(`${file.name}, ${result.width} × ${result.height} px`)}
        />
        {saved && <Text tone="subtle">Saved {saved}</Text>}
      </Stack>
    </div>
  );
}
```

### After a file is picked

FileTrigger checks the type and size, then the cropper frames the picked file.

```tsx
import { Button } from "@senvenli/react/action";
import { FileTrigger } from "@senvenli/react/form";
import { Text } from "@senvenli/react/display";
import { ImageCropper } from "@senvenli/react/form";
import { Stack } from "@senvenli/react/layout";
import { useState } from "react";

export default function Example() {
  const [picked, setPicked] = useState<File>();
  const [saved, setSaved] = useState<File>();
  return (
    <div className="flex max-w-xl flex-col gap-ds-150">
      <Stack space="space-150" align="start">
        <FileTrigger acceptedFileTypes={["image/jpeg", "image/png", "image/webp"]} maxSize={10_000_000} onSelect={([file]) => setPicked(file)}>
          <Button iconBefore="image-up">Choose a profile photo</Button>
        </FileTrigger>
        {saved && <Text tone="subtle">Saved {saved.name}</Text>}
      </Stack>
      {picked && (
        <ImageCropper
          src={picked}
          label="Profile photo"
          aspectRatio={1}
          maxOutputSize={512}
          onCrop={(file) => {
            setSaved(file);
            setPicked(undefined);
          }}
          onCancel={() => setPicked(undefined)}
        />
      )}
    </div>
  );
}
```

## Guidelines

### When to use it

- Before an uploaded image is saved: a cover photo, an avatar, a logo.

### Use something else when

- [file-upload](https://design.senvenli.com/docs/components/file-upload.md): Files are kept as picked, without framing.
- [image](https://design.senvenli.com/docs/components/image.md): The picture is only shown.

## Accessibility

Keyboard:

- Arrow keys: Move the image in the frame.
- + / -: Zoom in or out.

Built in:

- The frame announces its position and zoom.

You provide:

- What is being cropped, as its name.

## API reference

### ImageCropper

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| src | `string \| Blob` |  | yes | The picked file (from FileTrigger, already checked for size and type), or an image URL. A URL from another origin is loaded with CORS so the crop can be read back: its server must send `Access-Control-Allow-Origin`, or the image does not open (rather than failing later at save). |
| label | `string` |  | yes | What is being cropped ("Cover photo"); names the crop frame. |
| aspectRatio | `ImageCropperAspect` | `16 / 9` | no | 16:9 by default; `"free"` keeps the image's own shape. Ignored when presets are given. |
| aspectPresets | `readonly ImageCropperPreset[]` |  | no | Two or more shapes to choose from (a segmented control); the first is selected. |
| fit | `CropFit` | `"cover"` | no | `cover` (default) fills the frame; `contain` fits the whole image and leaves empty area. |
| background | `string` | `"#ffffff"` | no | The empty area's colour in `contain` when the output has no alpha (JPEG). White by default. |
| outputType | `CropOutputType` | `"image/jpeg"` | no | `image/jpeg` by default. PNG and WebP keep transparency. |
| quality | `number` | `0.9` | no | 0–1, for JPEG and WebP. 0.9 by default. |
| maxBytes | `number` |  | no | The largest file the surface takes, in bytes. A JPEG or WebP over it is encoded again at a quality 0.1 lower each time, down to `minimumQuality`; when even that is over, or a PNG is, nothing is handed to `onCrop` and the cropper says the image is over the limit (a smaller crop, by zooming in, or another image fits). |
| minimumQuality | `number` |  | no | The lowest quality `maxBytes` may step down to (0.9 keeps a hero or slide sharp). 0.1 by default; at most `quality`. |
| maxOutputSize | `number` | `4096` | no | The output's long edge in px at most (a surface's size, 2560 for a full-width photo): larger crops scale down, never up. 4096 by default, so a 48 MP phone photo stays within every browser's canvas limit. |
| minOutputSize | `number` |  | no | Under this long edge the warning shows; it never blocks. |
| fileName | `string` |  | no | The output file's name without extension; the source file's name by default. |
| onCrop | `(file: File, result: ImageCropperResult) => unknown` |  | yes |  |
| onCancel | `() => void` |  | no |  |

### Tokens it reads

`--ds-background-brand-bold`, `--ds-background-disabled`, `--ds-background-neutral`, `--ds-background-selected`, `--ds-blanket`, `--ds-border`, `--ds-border-bold`, `--ds-border-focused`, `--ds-border-selected`, `--ds-link`, `--ds-radius-full`, `--ds-radius-large`, `--ds-radius-medium`, `--ds-shadow-raised`, `--ds-space-050`, `--ds-space-100`, `--ds-space-150`, `--ds-space-300`, `--ds-space-400`, `--ds-surface-raised`, `--ds-surface-sunken`, `--ds-text`, `--ds-text-danger`, `--ds-text-disabled`, `--ds-text-subtle`, `--ds-text-subtlest`, `--ds-text-warning`

## Related

- [file-upload](https://design.senvenli.com/docs/components/file-upload.md)
