ngx-image-cropper

repository·master·Indexed 21 days ago

https://github.com/mawi137/ngx-image-cropper

An Angular component for image cropping that allows users to select images and manipulate a crop area. It supports multiple image sources including file events, URLs, Base64 strings, and Blobs, returning the cropped result as either a Base64 string or a Blob. Features include aspect ratio control, image transformations (rotate, scale, flip), output format selection (png, jpeg, webp, bmp, ico), and manual cropping via a crop() method. Version 9.0.0+ requires Angular 17.3+.

Tokens
8K
Snippets
18
Records
37
Agent score
72%

What's inside ngx-image-cropper

  1. Load an image into the cropper

    master

    To load an image, you must provide one of the following inputs. All inputs are optional, but at least one must be set:

    • imageChangedEvent: The FileEvent from a file input. Set to null to reset the cropper.
    • imageFile: A Blob(File) object. Set to null to reset the cropper.
    • imageBase64: A string containing a base64 encoded image.
    • imageURL: A string URL of an image. Note: If the image is from a different domain, CORS must be enabled on that domain.
  2. Configure image transformations and movement

    master

    Control how the image is manipulated within the cropper:

    • allowMoveImage: If true, allows the background image to be moved. When combined with transform, use two-way data binding [(transform)]="transform".
    • transform: An ImageTransform object to flip, rotate, and scale the image. Use two-way data binding [(transform)]="transform" if allowMoveImage is enabled.
    • canvasRotation: Rotates the canvas. Use increments of 90 degrees (e.g., 1 = 90deg, 2 = 180deg).
  3. Configure cropper aspect ratio and resizing

    master

    Use the following inputs to control the shape and size of the crop area:

    • aspectRatio: The width/height ratio (e.g., 1 / 1 for square, 16 / 9). Default is 1 / 1.
    • maintainAspectRatio: If true (default), keeps the width and height equal according to the aspectRatio.
    • containWithinAspectRatio: If true, adds padding around the image to make it fit the aspect ratio.
    • resizeToWidth: Resizes the cropped image to at most this width (in px). Set to 0 to disable.
    • resizeToHeight: Resizes the cropped image to at most this height (in px). Set to 0 to disable.
    • onlyScaleDown: If true, prevents smaller images from being scaled up when resizeToWidth or resizeToHeight is used.
  4. Configure cropper dimensions and constraints

    master

    Control the physical size of the cropper UI component using these inputs:

    • cropperStaticWidth: Sets a fixed width (in px) and disables resizing.
    • cropperStaticHeight: Sets a fixed height (in px) and disables resizing.
    • cropperMinWidth: The minimum width (in px) the cropper can be relative to the original image size.
    • cropperMaxWidth: The maximum width (in px) the cropper can be.
    • cropperMinHeight: The minimum height (in px) the cropper can be (ignored if maintainAspectRatio is true).
    • cropperMaxHeight: The maximum height (in px) the cropper can be.
  5. Configure output format and type

    master

    Define how the cropped image is returned:

    • format: The output file format. Supported values: png (always supported), jpeg, webp, bmp, ico. Default is png.
    • output: The output data type. Supported values: blob (most performant) or base64. Default is blob.
    • imageQuality: A number between 0 and 100 determining quality. Only applies when using jpeg or webp formats. Default is 92.
  6. Implement basic image cropping usage

    master

    To use the cropper, follow these steps:

    1. HTML: Add an <input type="file"> to capture the file change event and the <image-cropper> component to handle the cropping logic.
    2. TypeScript: Import ImageCropperComponent and its related types. Use DomSanitizer to safely display the resulting objectUrl in an <img> tag.
    3. Workflow:
      • The fileChangeEvent updates imageChangedEvent.
      • The cropper reacts to imageChangedEvent by loading the image.
      • The imageCropped event provides the cropped result (as a Base64 string or a Blob) whenever the user finishes an interaction.
    <input type="file" (change)="fileChangeEvent($event)" />
    
    <image-cropper
        [imageChangedEvent]="imageChangedEvent"
        [maintainAspectRatio]="true"
        [aspectRatio]="4 / 3"
        format="png"
        (imageCropped)="imageCropped($event)"
        (imageLoaded)="imageLoaded($event)"
        (cropperReady)="cropperReady()"
        (loadImageFailed)="loadImageFailed()"
    ></image-cropper>
    
    <img [src]="croppedImage" />
    import { ImageCropperComponent, ImageCroppedEvent, LoadedImage } from 'ngx-image-cropper';
    import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
    import { Component } from '@angular/core';
    
    @Component({
      standalone: true,
      imports: [ImageCropperComponent]
    })
    export class YourComponent {
        imageChangedEvent: Event | null = null;
        croppedImage: SafeUrl  = '';
        
        constructor(private sanitizer: DomSanitizer) {}
    
        fileChangeEvent(event: Event): void {
            this.imageChangedEvent = event;
        }
    
        imageCropped(event: ImageCroppedEvent) {
          // Use event.objectUrl for previewing via DomSanitizer
          this.croppedImage = this.sanitizer.bypassSecurityTrustUrl(event.objectUrl);
          // Use event.blob to upload the cropped image to a server
        }
    
        imageLoaded(image: LoadedImage) {
            // Handle image loaded
        }
    
        cropperReady() {
            // Handle cropper ready
        }
    
        loadImageFailed() {
            // Handle load failure
        }
    }
  7. Use the crop() method manually

    master

    If you want to control exactly when the cropping happens, set the autoCrop input to false. You can then trigger the crop manually using the crop() method via @ViewChild.

    @ViewChild(ImageCropperComponent) imageCropper: ImageCropperComponent;
    
    // ...
    
    this.imageCropper.crop('blob').then((event: ImageCroppedEvent) => {
      console.log(event.blob);
    });

    When output is set to 'blob', the method returns a Promise<ImageCroppedEvent>. If set to 'base64', it returns the event directly.

  8. Configure CropperOptions

    master

    The CropperOptions interface defines the configuration for the ngx-image-cropper component. It controls the output format, image quality, aspect ratio behavior, and the visual appearance of the cropper UI.

    const options: CropperOptions = {
      format: 'png',
      output: 'base64',
      aspectRatio: 16 / 9,
      maintainAspectRatio: true,
      autoCrop: true,
      imageQuality: 90,
      // ... other options
    };
  9. Reference: CropperPosition Interface

    master

    Defines the coordinates of the cropping area.

    | Property | Type   | Description |
    |----------|--------|-------------|
    | `x1`     | number | X position of first coordinate (in px) |
    | `y1`     | number | Y position of first coordinate (in px) |
    | `x2`     | number | X position of second coordinate (in px) |
    | `y2`     | number | Y position of second coordinate (in px) |
  10. Reference: ImageCropperComponent Inputs

    master

    A complete list of available inputs for the ImageCropperComponent.

    | Name                       | Type                    | Default      | Description |
    |----------------------------|-------------------------|--------------|-------------|
    | `imageChangedEvent`        | FileEvent               |              | The change event from your file input (set to `null` to reset the cropper) |
    | `imageFile`                | Blob(File)               |              | The file you want to change (set to `null` to reset the cropper) |
    | `imageBase64`               | string                  |              | Set a base64 image directly |
    | `imageURL`                 | string                  |              | Set a URL to get the image from (requires CORS) |
    | `imageAltText`             | string                  |              | Alternative text for accessibility |
    | `cropperFrameAriaLabel`    | string                  | 'Crop photo' | Aria-label for the cropper frame |
    | `format`                   | string                  | png          | Output format (png, jpeg, webp, bmp, ico) |
    | `output`                   | string                  | blob         | Output type (blob or base64) |
    | `aspectRatio`              | number                  | 1 / 1        | The width / height ratio |
    | `maintainAspectRatio`      | boolean                 | true         | Keep width and height according to aspectRatio |
    | `containWithinAspectRatio` | boolean                 | false        | Add padding to fit aspect ratio |
    | `resizeToWidth`            | number                  | 0 (disabled) | Max width (px) |
    | `resizeToHeight`           | number                  | 0 (disabled) | Max height (px) |
    | `cropperStaticWidth`       | number                  | 0 (disabled) | Fixed width (px) |
    | `cropperStaticHeight`      | number                  | 0 (disabled) | Fixed height (px) |
    | `cropperMinWidth`          | number                  | 0 (disabled) | Min width (px) |
    | `cropperMinHeight`         | number                  | 0 (disabled) | Min height (px) |
    | `cropperMaxWidth`          | number                  | 0 (disabled) | Max width (px) |
    | `cropperMaxHeight`         | number                  | 0 (disabled) | Max height (px) |
    | `initialStepSize`          | number                  | 3 (px)       | Keyboard movement step size |
    | `onlyScaleDown`            | boolean                 | false        | Prevent scaling up when resizing |
    | `cropper`                  | CropperPosition         |              | Overwrite cropper coordinates |
    | `roundCropper`             | boolean                 | false        | Enable round cropper |
    | `imageQuality`             | number                  | 92           | Quality for jpeg/webp (0-100) |
    | `autoCrop`                 | boolean                 | true         | Emit image on every change |
    | `alignImage`               | 'left' or 'center'      | 'center'     | Image alignment |
    | `backgroundColor`         | string                  |              | CSS color for transparent pixels |
    | `hideResizeSquares`        | boolean                 | false        | Disable resize squares |
    | `disabled`                 | boolean                 | false        | Disable component |
    | `canvasRotation`           | number                  | 0            | Rotate canvas (1=90deg, 2=180deg...) |
    | `transform`                | ImageTransform          | {}           | Flip, rotate and scale image |
    | `allowMoveImage`           | boolean                 | false        | Allow background image movement |
    | `hidden`                   | boolean                 | false        | Hide component |
    | `options`                  | Partial<CropperOptions> | undefined    | Patch multiple options at once |