Skip to content

weblineindia/Angular-Image-Crop-Upload

Repository files navigation

AngularJS - Image Upload with Crop

AngularJS based reusable component for Image upload with cropping.

Table of contents

Demo

Getting started

npm install angular-weblineindia-image-crop-upload --save

Example usage

Add the ImageCropperModule to the imports of the module which will be using the Image Cropper.

import { NgModule } from '@angular/core';
import { ImageCropperModule } from 'angular-weblineindia-image-crop-upload';

@NgModule({
    imports: [
        ...
        ImageCropperModule
    ],
    declarations: [
        ...
    ],
    exports: [
        ...
    ],
    providers: [
        ...
    ]
})
export class YourModule {
}

Add the element to your HTML:

<input type="file" (change)="fileChangeEvent($event)" />

<image-cropper
    [imageChangedEvent]="imageChangedEvent"
    [maintainAspectRatio]="true"
    [aspectRatio]="4 / 3"
    format="png"
    (imageCropped)="imageCropped($event)"
    (imageLoaded)="imageLoaded()"
    (cropperReady)="cropperReady()"
    (loadImageFailed)="loadImageFailed()"
></image-cropper>

<img [src]="croppedImage" />

And add this to your ts file:

import { ImageCroppedEvent } from 'angular-weblineindia-image-crop-upload';

export class YourComponent {
    imageChangedEvent: any = '';
    croppedImage: any = '';

    fileChangeEvent(event: any): void {
        this.imageChangedEvent = event;
    }
    imageCropped(event: ImageCroppedEvent) {
        this.croppedImage = event.base64;
    }
    imageLoaded() {
        // show cropper
    }
    cropperReady() {
        // cropper ready
    }
    loadImageFailed() {
        // show message
    }
}

When you choose a file from the file input, it will trigger fileChangeEvent. That event is then passed to the image cropper through imageChangedEvent which will load the image into the cropper. Everytime you release the mouse, the imageCropped event will be triggerd with the cropped image as a Base64 string in its payload.

API

All inputs are optional. Either the imageChangedEvent, imageBase64 or imageFile should be set to load an image into the cropper.

Inputs