# Image Editor
This package is still experimental. “Experimental” means this is an early implementation subject to drastic and breaking changes.
An image editor: a canvas where a person pans, zooms, rotates, flips and crops an image, and functions that describe the edit for saving. The media editor is built on it.
This package replaces `@wordpress/image-cropper`, which is deprecated and will be removed in a later release.
## Installation
Install the module
```bash
npm install @wordpress/image-editor --save
```
## Styles
The canvas needs its stylesheet for layout. Load `build-style/style.css` from your app's Sass:
```scss
@use "@wordpress/image-editor/build-style/style.css";
```
Or import it from JavaScript:
```js
import '@wordpress/image-editor/build-style/style.css';
```
The canvas follows WordPress Design System colours and spacing when their tokens are present. A surrounding `ThemeProvider` can supply a light or dark palette. The built stylesheet also supplies standalone defaults when the tokens are absent. The grid stays translucent white because it sits over the image.
Set these CSS custom properties on a parent element or a class passed to `ImageEditorCanvas` through `className` to change its appearance without targeting its internal elements:
| Property | Changes |
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| `--wp-image-editor-accent-color` | Handle borders and keyboard focus colour. Defaults to the admin theme colour, or blue outside WordPress. |
| `--wp-image-editor-foreground-color` | Crop outline at rest and dimensions tooltip text. The focused outline uses the accent colour. |
| `--wp-image-editor-surface-color` | Handle fill, dimensions tooltip background and the inner focus ring. |
| `--wp-image-editor-dimming-color` | Colour outside the crop. During a drag, the same colour is used at two-thirds opacity. |
| `--wp-image-editor-grid-color` | Rule-of-thirds lines. |
| `--wp-image-editor-canvas-inset` | Space around the editing surface. Defaults to 24px and cannot go below 22px, so resize handles remain reachable. |
For example, `` can use:
```css
.my-cropper {
--wp-image-editor-accent-color: rebeccapurple;
}
.my-cropper.is-dark {
--wp-image-editor-foreground-color: #f0f0f0;
--wp-image-editor-surface-color: #1e1e1e;
--wp-image-editor-dimming-color: rgb( 0 0 0 / 60% );
}
```
To use the design tokens outside WordPress, install `@wordpress/theme` and load its `design-tokens.css` in your app. The image editor runs without it, and your custom properties take precedence over the design tokens.
## Outside WordPress
The package needs no WordPress site, and nothing it imports talks to one.
- The examples import React hooks from `@wordpress/element`, which re-exports React. Import them from `react` instead if you prefer.
- The editor's own text, such as the labels on the resize handles and what a screen reader announces, is in English unless you give `@wordpress/i18n` your translations.
## Quick Start
You keep the editor's state, and the controller hands you each change.
```tsx
import { useState } from '@wordpress/element';
import {
ImageEditorCanvas,
createImageEditorState,
useImageEditor,
} from '@wordpress/image-editor';
function MyImageEditor( { src }: { src: string } ) {
const [ state, setState ] = useState( () => createImageEditorState() );
const controller = useImageEditor( { state, onChange: setState } );
return (
);
}
```
## API
### `ImageEditorCanvas`
The canvas the person edits the image on. It fills its parent, so render it inside a sized element.
- `src` (required): the image URL.
- `controller` (required): the controller from `useImageEditor`.
- `showGrid`: show the rule-of-thirds grid: `true`, `false` or `'interactive'` (only while the crop is being changed). Defaults to `false`.
- `showDimming`: dim the image outside the crop area. Defaults to `true`.
- `showDimensions`: show the crop size in pixels while resizing. Defaults to `true`.
- `freeformCrop`: show resize handles so the crop area can be resized and moved. Defaults to `true`. When `false`, the crop area is fixed and centred, and the image pans and zooms under it.
- `focusOnMount`: focus the crop area when it mounts. Defaults to `false`.
- `disabled`: ignore all crop interaction, for example while saving, so the edit cannot change after saving starts. A gesture already in progress is cancelled. Defaults to `false`.
- `onImageLoaded( size )`: called with the image's natural size when the image loads.
- `onImageError()`: called when the image fails to load.
- `onGestureStart()`: called when a drag, resize or pinch starts. Use it with `onGestureEnd` to record a gesture as one undo entry.
- `onGestureEnd()`: called when a drag, resize or pinch ends.
- `className`: an extra class for the container.
### `useImageEditor( { state, onChange } )`
React hook that returns the editor's controller. Pass the current state and a function that stores the next one. `onChange( nextState, { isEdit } )` gets `isEdit: false` for changes the person did not make, such as an image loading or the crop being refitted after a window resize, which usually should not get an undo entry.
The controller has:
- `state`: the current state.
- `setPan( { x, y } )`, `setZoom( zoom )`, `setRotation( degrees )`, `snapRotate90( 1 | -1 )`, `setFlip( { horizontal, vertical } )`, `toggleFlip( 'horizontal' | 'vertical' )`, `setCropRect( { x, y, width, height } )` and `setAspectRatio( ratio )` to change the edit. The crop area is in fractions of the view, from 0 to 1. The pan is an offset from the centre, so it is signed, and how far it can go depends on the zoom and the crop, because the image has to cover the crop. `setAspectRatio( ratio )` reshapes the crop to the largest box of that ratio, and `setAspectRatio( undefined )` unlocks it. While a ratio is locked, the crop always has that ratio: a crop that does not match, from `setCropRect` or a state you pass in, keeps its centre and width and takes the height the ratio needs.
- `setImage( image )` to load an image. The canvas calls it when `src` loads. The first image keeps the state you started from, such as an edit you saved earlier. Replacing or clearing a loaded image starts fresh: no pan, zoom, rotation, flip or crop from the old image, but a locked ratio stays.
- `reset()` to go back to the clean state, and `isDirty`, which is `true` when the pan, zoom, rotation, flip or crop differs from that state. The clean state is the state you started from, as the editor settled it before the person made an edit: loading the image and fitting the crop to a locked ratio are not edits. So `reset()` keeps a locked ratio only when the state you started from had one; a ratio locked later is an edit, and reset undoes it along with the rest. Locking a ratio usually makes the edit dirty, because it reshapes the crop. Unlocking does not, and nor does locking a ratio the crop already has.
- `minZoom`, `maxZoom` and `maxRotationOffset`: the limits for building zoom and rotation controls. `minZoom` is the smallest zoom that still covers the crop area, so it changes with the edit.
### `ImageEditorState`, `createImageEditorState( options? )`
The editor's state, and the state an editor starts from. Pass `image` when you already have one, and `aspectRatio` to lock the crop from the start; both are optional. Read the state, store it and pass it back, but create it with `createImageEditorState` and change it only through the controller: it also carries values the editor keeps for itself.
### `areImageEditorStatesEqual( a, b )`
Whether two states have the same public edit fields, ignoring tiny floating-point differences. The values the editor keeps for later rotations do not count. Use it to skip entries that change nothing in your own undo history.
### `getOutputSize( state )`
The dimensions that the edit from `getImageEdit` would produce on the image in `state.image`. A nearly full crop that `getImageEdit` omits gives the full image dimensions. Use this for a size readout or a minimum-size check against the loaded image. A processor that edits a different file or rounds pixels may produce different dimensions. A dimension within a millionth of a pixel of a whole number is returned as that number, so nine tenths of a 1600 pixel wide image is 1440, not 1439.9999999999998. Returns `null` when no image has loaded.
### `getImageEdit( state )`
Use it when saving. The editor stores where the image sits, how far it is zoomed, and a crop area measured against the view. `getImageEdit` describes the same result against the full-size image loaded in `state.image`, which may itself be a file someone edited before.
The edit has an optional `flip`, `rotation` and `crop`. Apply them in that order; anything absent needs nothing done. With exactly one axis flipped, `rotation` is 360 minus `state.rotation`, because the flip comes first. The crop is given as fractions of the image after rotation; a fraction within a millionth of 0 or 1 is returned as 0 or 1. An edit with no parts means there is nothing to apply, and `null` means no image has loaded. A locked ratio can produce a crop before the person edits anything.
### `mapImageEdit( edit, handlers )`
Use it to turn an edit into a list of instructions for something that applies them one at a time, such as the WordPress media REST endpoint. `handlers` has one function for each part, `flip`, `rotation` and `crop`; each is called only when the edit has that part, and the results come back in the order the parts apply. The order matters because `rotation` is measured after the flip and `crop` after both, so instructions applied in another order frame a different part of the image.
### `applyImageEdit( state, edit, options? )`
The reverse of `getImageEdit`: it turns an `ImageEdit` into an editor state, so code can set the edit.
```ts
const result = applyImageEdit( state, {
rotation: 90,
crop: { x: 0, y: 0, width: 0.5, height: 1 },
} );
if ( 'state' in result ) {
setState( result.state );
}
```
The edit replaces the current one. It is not merged with it. Every part is optional, and a part you leave out is reset:
- No `flip`: the image is not flipped.
- No `rotation`: the image is not rotated.
- No `crop`: the editor picks one, as when the image is rotated by hand. At a quarter turn that is the whole image.
Passing `{ rotation: 90 }` to an image you have cropped gives a rotated image with no crop. To keep the crop, pass it again along with the rotation: every call describes the whole result. The parts apply in order, flip, then rotation, then the crop on the flipped and rotated image, so a crop's numbers mean a different region once the rotation changes.
From `state`, only the image and the locked ratio are kept. The pan and zoom are worked out again: the crop is centered and zoomed in, as after a resize.
The image always covers the crop. A crop it does not cover is fitted the way the editor fits one: it shrinks around its center, keeping its shape, until the image can cover it, then moves the shortest way inside. Under a locked ratio, the crop keeps its center and width and takes the height the ratio needs. Pass `{ strict: true }` to reject such a crop instead of fitting it. Use it when code must know the crop was taken as given. A missing crop is still the editor's choice, so `{ rotation: 5 }` applies either way.
The result is `{ state }`, which you store like any other change, or `{ rejected }` with the reason the edit could not be applied:
- `'no-image'`: no image with a usable size has loaded.
- `'invalid'`: a number is not finite, a flip value is not `true` or `false`, or the crop is under one pixel wide or high.
- `'locked-ratio'`, strict mode only: the crop is not the shape of the locked ratio. Without the lock, the edit would apply.
- `'outside-image'`, strict mode only: the crop reaches outside the image.
### `exportImage( state, options? )`
Use it when the edited image is uploaded as a new file, rather than applied to the original by a server. It loads the image in `state.image`, draws the region the crop frames with the flip, rotation and zoom applied, and resolves with a `Blob` whose dimensions are the ones `getOutputSize( state )` reports. `options.type` is the MIME type, `image/png` by default, and `options.quality` is the quality for lossy types, from 0 to 1.
It runs only in a browser. It rejects when no image has loaded, when the image fails to load, or when the browser refuses to read the canvas: the image is loaded with `crossOrigin` set to `anonymous`, so a source on another origin needs CORS headers.
## Not Yet Included
- **A self-contained mode**, where `useImageEditor()` keeps the state itself, for an editor without its own undo history.
## More
- [Architecture](/packages/image-editor/docs/architecture.md)
- [Recipes](/packages/image-editor/docs/recipes.md)
## Contributing to this package
This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to [npm](https://www.npmjs.com/) and used by [WordPress](https://make.wordpress.org/core/) as well as other software projects.
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main [contributor guide](https://github.com/WordPress/gutenberg/tree/HEAD/CONTRIBUTING.md).
