# Angular Image Cropper Component

ImageCropper crops an image with a fixed crop area over an image that moves, zooms and rotates underneath, with the mouse, a finger or the keyboard, and gives the cropped image as a Blob. Free, without any dependency.

## Basic

ImageCropper takes an image in src : an URL, a File or a Blob . The crop area stays fixed in the middle and the image moves and zooms underneath: drag it with the mouse or a finger, zoom with the wheel, the touchpad or a pinch. The image always covers the crop area. [(crop)] gives the cropped area in pixels of the source image, with its percentages, on every change.

```typescript
import { Component } from '@angular/core';
import { ImageCropperCrop, ImageCropperModule } from '@exhaustive-ui/core/imagecropper';

@Component({
    template: `
        <div class="card">
            <p-image-cropper src="/demo/galleria/galleria1.jpg" [(crop)]="crop" ariaLabel="Crop the landscape" />
            @if (crop) {
                <p class="mt-4 mb-0 text-sm text-muted-color">x: {{ crop.x }}, y: {{ crop.y }}, width: {{ crop.width }}, height: {{ crop.height }}</p>
            }
        </div>
    `,
    standalone: true,
    imports: [ImageCropperModule]
})
export class ImagecropperBasicDemo {
    crop: ImageCropperCrop | null = null;
}
```

## Aspect Ratio

aspectRatio is the width of the crop area divided by its height, 4 / 3 by default. With 'free' , the crop area has handles on its sides and corners, and Alt with the arrow keys resizes it; it stays centered, so it grows on both sides. minCropSize and maxCropSize limit the cropped area in pixels of the source image, and so the zoom.

```typescript
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ImageCropperModule } from '@exhaustive-ui/core/imagecropper';
import { SelectButtonModule } from '@exhaustive-ui/core/selectbutton';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p-select-button [options]="ratios" [(ngModel)]="ratio" optionLabel="label" optionValue="value" [allowEmpty]="false" ariaLabelledBy="aspect-ratio-label" />
            <span id="aspect-ratio-label" class="sr-only">Aspect ratio</span>
            <p-image-cropper src="/demo/galleria/galleria1.jpg" [aspectRatio]="ratio" [minCropSize]="{ width: 100, height: 100 }" ariaLabel="Crop with an aspect ratio" />
        </div>
    `,
    standalone: true,
    imports: [FormsModule, ImageCropperModule, SelectButtonModule]
})
export class ImagecropperAspectratioDemo {
    ratio: number | 'free' = 16 / 9;

    ratios = [
        { label: '16:9', value: 16 / 9 },
        { label: '4:3', value: 4 / 3 },
        { label: '1:1', value: 1 },
        { label: 'Free', value: 'free' }
    ];
}
```

## Round Crop

cropShape="round" shows a round crop area, for an avatar. With an aspectRatio other than 1 it is an ellipse. The cropped image is cut to the same shape, with transparent corners: keep a type with transparency, such as PNG or WebP, or pass round: false to getCroppedImage to keep the corners. showGrid hides the rule of thirds grid.

```typescript
import { Component } from '@angular/core';
import { ImageCropperModule } from '@exhaustive-ui/core/imagecropper';

@Component({
    template: `
        <div class="card">
            <p-image-cropper src="/demo/galleria/galleria5.jpg" [aspectRatio]="1" cropShape="round" [showGrid]="false" ariaLabel="Crop the avatar" />
        </div>
    `,
    standalone: true,
    imports: [ImageCropperModule]
})
export class ImagecropperRoundDemo {
}
```

## Zoom and Rotation

zoom and rotation are models, bound two-way with sliders here. The zoom stays between minZoom and maxZoom , 1 and 3 by default, and never below what keeps the crop area covered: a rotated image zooms in by itself. The rotate method turns the image by a number of degrees and keeps the rotation between -180 and 180; flipHorizontal and flipVertical mirror it, and reset brings everything back.

```typescript
import { DecimalPipe } from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { ImageCropperModule } from '@exhaustive-ui/core/imagecropper';
import { SliderModule } from '@exhaustive-ui/core/slider';
import { arrowsH, refresh, replay, undo } from '@exhaustive-ui/icons/round';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p-image-cropper #cropper src="/demo/galleria/galleria1.jpg" [(zoom)]="zoom" [(rotation)]="rotation" [(flipHorizontal)]="flipped" ariaLabel="Crop with the controls" />
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                <div class="flex flex-col gap-3">
                    <span id="zoom-label" class="text-sm font-medium">Zoom {{ zoom * 100 | number: '1.0-0' }}%</span>
                    <p-slider [(ngModel)]="zoom" [min]="1" [max]="3" [step]="0.01" ariaLabelledBy="zoom-label" />
                </div>
                <div class="flex flex-col gap-3">
                    <span id="rotation-label" class="text-sm font-medium">Rotation {{ rotation | number: '1.0-0' }}°</span>
                    <p-slider [(ngModel)]="rotation" [min]="-180" [max]="180" ariaLabelledBy="rotation-label" />
                </div>
            </div>
            <div class="flex flex-wrap gap-2">
                <p-button [icon]="replay" severity="secondary" outlined ariaLabel="Rotate left" (onClick)="cropper.rotate(-90)" />
                <p-button [icon]="refresh" severity="secondary" outlined ariaLabel="Rotate right" (onClick)="cropper.rotate(90)" />
                <p-button [icon]="arrowsH" label="Mirror" severity="secondary" outlined (onClick)="flipped = !flipped" />
                <p-button [icon]="undo" label="Reset" severity="secondary" outlined (onClick)="cropper.reset()" />
            </div>
        </div>
    `,
    standalone: true,
    imports: [DecimalPipe, FormsModule, ButtonModule, ImageCropperModule, SliderModule]
})
export class ImagecropperControlsDemo {
    replay = replay;
    refresh = refresh;
    arrowsH = arrowsH;
    undo = undo;

    zoom = 1;

    rotation = 0;

    flipped = false;
}
```

## Preview

getCroppedDataUrl draws the cropped area, with its rotation and flip, and gives it as a data URL, here at most 160 pixels wide for a live thumbnail updated on every cropChange . onCropComplete is emitted once an interaction ends, when the pointer is released or the wheel and the keys stop: the place for heavier work.

```typescript
import { Component, signal, viewChild } from '@angular/core';
import { ImageCropper, ImageCropperModule } from '@exhaustive-ui/core/imagecropper';

@Component({
    template: `
        <div class="card flex flex-col md:flex-row gap-6 items-start">
            <p-image-cropper class="flex-1" src="/demo/galleria/galleria1.jpg" [aspectRatio]="1" cropShape="round" (cropChange)="updatePreview()" (onCropComplete)="completed.set(completed() + 1)" ariaLabel="Crop with a preview" />
            <div class="flex flex-col items-center gap-2">
                @if (preview()) {
                    <img [src]="preview()" alt="Preview of the cropped image" class="w-40 h-40 rounded-full border border-surface" />
                }
                <span class="text-sm text-muted-color">Interactions completed: {{ completed() }}</span>
            </div>
        </div>
    `,
    standalone: true,
    imports: [ImageCropperModule]
})
export class ImagecropperPreviewDemo {
    cropper = viewChild.required(ImageCropper);

    preview = signal<string | null>(null);

    completed = signal(0);

    private pending = false;

    updatePreview() {
        // one thumbnail per frame, however often the crop changes
        if (this.pending) return;
        this.pending = true;
        requestAnimationFrame(async () => {
            this.pending = false;
            try {
                this.preview.set(await this.cropper().getCroppedDataUrl({ maxWidth: 160 }));
            } catch {
                this.preview.set(null);
            }
        });
    }
}
```

## Upload Flow

A File picked with FileInput, or FileUpload, goes straight into src : the component creates its object URL and revokes it when the file changes. getCroppedImage gives the result as a Blob , here a JPEG at most 1024 pixels wide, ready to be sent in a FormData . ImageCropper is not a form control: its value would be the crop rectangle, while a form wants the cropped file, which only exists once getCroppedImage resolves. Set your form control with that Blob, or keep the [(crop)] rectangle and crop on the server.

```typescript
import { DecimalPipe } from '@angular/common';
import { Component, DestroyRef, inject, signal, viewChild } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { FileInputModule } from '@exhaustive-ui/core/fileinput';
import { ImageCropper, ImageCropperModule } from '@exhaustive-ui/core/imagecropper';
import { check } from '@exhaustive-ui/icons/round';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p-file-input [(ngModel)]="file" (ngModelChange)="clear()" accept="image/*" [multiple]="false" />
            @if (file) {
                <p-image-cropper [src]="file" [aspectRatio]="16 / 9" ariaLabel="Crop the selected image" />
                <div class="flex flex-wrap items-center gap-4">
                    <p-button [icon]="check" label="Crop" (onClick)="cropImage()" />
                    @if (result(); as cropped) {
                        <span class="text-sm">{{ cropped.width }} × {{ cropped.height }} JPEG, {{ cropped.size / 1024 | number: '1.0-1' }} KB</span>
                    }
                </div>
                @if (result(); as cropped) {
                    <img [src]="cropped.url" alt="Cropped image" class="max-w-full rounded-border" [style.width.px]="cropped.width / 2" />
                }
            }
        </div>
    `,
    standalone: true,
    imports: [DecimalPipe, FormsModule, ButtonModule, FileInputModule, ImageCropperModule]
})
export class ImagecropperUploadDemo {
    check = check;

    cropper = viewChild(ImageCropper);

    file: File | null = null;

    result = signal<{ url: string; size: number; width: number; height: number } | null>(null);

    constructor() {
        inject(DestroyRef).onDestroy(() => this.revoke());
    }

    async cropImage() {
        const cropper = this.cropper();
        if (!cropper) return;
        const blob = await cropper.getCroppedImage({ type: 'image/jpeg', quality: 0.9, maxWidth: 1024 });
        const bitmap = await createImageBitmap(blob);
        this.revoke();
        this.result.set({ url: URL.createObjectURL(blob), size: blob.size, width: bitmap.width, height: bitmap.height });
        bitmap.close();
        // const body = new FormData();
        // body.append('avatar', blob, 'avatar.jpg');
    }

    clear() {
        this.revoke();
        this.result.set(null);
    }

    private revoke() {
        const current = this.result();
        if (current) URL.revokeObjectURL(current.url);
    }
}
```

## Template

The empty template replaces the message shown without an image, loading the spinner shown while it loads, and error the message shown when it can not be loaded; the error template receives the source and a reload function. onImageLoad gives the size of the image, and onImageError the failed source.

```typescript
import { Component, signal } from '@angular/core';
import { ButtonModule } from '@exhaustive-ui/core/button';
import { ImageCropperModule } from '@exhaustive-ui/core/imagecropper';
import { exclamationCircle, image as imageIcon, spinner as spinnerIcon } from '@exhaustive-ui/icons/round';
import { SvgIcon } from '@exhaustive-ui/core/icon';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <div class="flex flex-wrap gap-2">
                <p-button label="Load a photo" severity="secondary" outlined (onClick)="src.set('/demo/galleria/galleria3.jpg')" />
                <p-button label="Load a broken link" severity="secondary" outlined (onClick)="src.set('/demo/galleria/missing.jpg')" />
                <p-button label="Clear" severity="secondary" outlined (onClick)="src.set(null)" />
            </div>
            <p-image-cropper [src]="src()" ariaLabel="Crop with templates">
                <ng-template #empty>
                    <svg pIcon [icon]="imageIcon" class="!text-3xl" aria-hidden="true"></svg>
                    <span>Choose a photo to crop</span>
                </ng-template>
                <ng-template #loading>
                    <svg pIcon [icon]="spinnerIcon" spin class="!text-2xl" aria-hidden="true"></svg>
                    <span>Preparing the photo…</span>
                </ng-template>
                <ng-template #error let-reload="reload">
                    <svg pIcon [icon]="exclamationCircle" class="!text-3xl" aria-hidden="true"></svg>
                    <span>This photo is not available.</span>
                    <p-button label="Try again" size="small" severity="secondary" (onClick)="reload()" />
                </ng-template>
            </p-image-cropper>
        </div>
    `,
    standalone: true,
    imports: [SvgIcon, ButtonModule, ImageCropperModule]
})
export class ImagecropperTemplateDemo {
    imageIcon = imageIcon;
    spinnerIcon = spinnerIcon;
    exclamationCircle = exclamationCircle;

    src = signal<string | null>(null);
}
```

## Accessibility

Screen Reader The crop area is a focusable element with the application role, so that screen readers pass the arrow keys to it, and the "image cropper" role description. Its name is "Crop area" by default; give it a better one with ariaLabel or ariaLabelledBy . It is described with aria-describedby by the keyboard instructions, which mention resizing when the aspect ratio is free. The image takes its text alternative from alt , empty by default. The grid and the resize handles are hidden from assistive technologies. A polite live region announces the result of every key: "Crop area at 25% from the left and 40% from the top", "Zoom 150%", "Rotation 90 degrees" or "Crop area 640 by 480 pixels". The loading message is a status, and the error message an alert. Every text can be translated with labels . The arrow keys and the coordinates are physical directions, also in right-to-left layouts, since the image itself is not mirrored. Zoom and rotation changes made with the keyboard or the methods are animated, except when the user prefers reduced motion.

## Pass Through Options

| Name | Type | Description |
|------|------|-------------|
| root | PassThroughOption<HTMLElement, I> | Used to pass attributes to the root's DOM element. |
| viewport | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the viewport, the area that clips the image and receives the pointer. |
| image | PassThroughOption<HTMLImageElement, I> | Used to pass attributes to the image's DOM element. |
| cropArea | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the focusable crop area, which dims everything around it. |
| grid | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the rule of thirds grid. |
| gridLine | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to a line of the grid. |
| handle | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to a resize handle of the crop area, shown with a free aspect ratio. |
| loading | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the loading message. |
| loadingIcon | PassThroughOption<SVGElement, I> | Used to pass attributes to the loading icon. |
| error | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the error message. |
| errorIcon | PassThroughOption<SVGElement, I> | Used to pass attributes to the error icon. |
| empty | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the message shown without an image. |

## Theming

### CSS Classes

| Class | Description |
|-------|-------------|
| p-imagecropper | Class name of the root element |
| p-imagecropper-viewport | Class name of the viewport that clips the image |
| p-imagecropper-image | Class name of the image |
| p-imagecropper-crop-area | Class name of the crop area |
| p-imagecropper-grid | Class name of the rule of thirds grid |
| p-imagecropper-grid-line | Class name of a grid line |
| p-imagecropper-handle | Class name of a resize handle |
| p-imagecropper-loading | Class name of the loading message |
| p-imagecropper-loading-icon | Class name of the loading icon |
| p-imagecropper-error | Class name of the error message |
| p-imagecropper-error-icon | Class name of the error icon |
| p-imagecropper-empty | Class name of the message shown without an image |

### Design Tokens

| Token | CSS Variable | Description |
|-------|--------------|-------------|
| imagecropper.background | --p-imagecropper-background | Background of the area around the image |
| imagecropper.height | --p-imagecropper-height | Height of the component |
| imagecropper.border.radius | --p-imagecropper-border-radius | Border radius of the component |
| imagecropper.transition.duration | --p-imagecropper-transition-duration | Duration of the zoom and rotation transitions of the keyboard and the methods |
| imagecropper.overlay.background | --p-imagecropper-overlay-background | Background that dims the image around the crop area |
| imagecropper.crop.area.border.width | --p-imagecropper-crop-area-border-width | Border width of the crop area |
| imagecropper.crop.area.border.color | --p-imagecropper-crop-area-border-color | Border color of the crop area |
| imagecropper.crop.area.focus.ring.width | --p-imagecropper-crop-area-focus-ring-width | Focus ring width of the crop area |
| imagecropper.crop.area.focus.ring.style | --p-imagecropper-crop-area-focus-ring-style | Focus ring style of the crop area |
| imagecropper.crop.area.focus.ring.color | --p-imagecropper-crop-area-focus-ring-color | Focus ring color of the crop area |
| imagecropper.crop.area.focus.ring.offset | --p-imagecropper-crop-area-focus-ring-offset | Focus ring offset of the crop area |
| imagecropper.crop.area.focus.ring.shadow | --p-imagecropper-crop-area-focus-ring-shadow | Focus ring shadow of the crop area |
| imagecropper.grid.color | --p-imagecropper-grid-color | Color of the grid lines |
| imagecropper.grid.width | --p-imagecropper-grid-width | Width of the grid lines |
| imagecropper.handle.size | --p-imagecropper-handle-size | Size of a resize handle |
| imagecropper.handle.background | --p-imagecropper-handle-background | Background of a resize handle |
| imagecropper.handle.border.color | --p-imagecropper-handle-border-color | Border color of a resize handle |
| imagecropper.handle.border.radius | --p-imagecropper-handle-border-radius | Border radius of a resize handle |
| imagecropper.message.gap | --p-imagecropper-message-gap | Gap between the icon and the text of the loading, error and empty messages |
| imagecropper.message.padding | --p-imagecropper-message-padding | Padding of the messages |
| imagecropper.message.color | --p-imagecropper-message-color | Text color of the messages |
| imagecropper.message.font.size | --p-imagecropper-message-font-size | Font size of the messages |
| imagecropper.error.icon.color | --p-imagecropper-error-icon-color | Color of the error icon |

