import { Component , OnInit , ViewEncapsulation , ElementRef , ViewChild , Input , EventEmitter , Output } from '@angular/core' ; import Cropper from 'cropperjs' ; export interface ImageCropperSetting { width : number ; height : number ; } export interface ImageCropperResult { imageData : Cropper . ImageData ; cropData : Cropper . CropBoxData ; blob ? : Blob ; dataUrl ? : string ; } @ Component ( { selector : 'angular-cropper' , templateUrl : './cropper.component.html' , styleUrls : [ './cropper.component.css' ] , encapsulation : ViewEncapsulation . None } ) export class CropperComponent implements OnInit { @ ViewChild ( 'image' ) image : ElementRef ; @ Input ( ) imageUrl : any ; @ Input ( ) settings : ImageCropperSetting ; @ Input ( ) cropbox : Cropper . CropBoxData ; @ Input ( ) loadImageErrorText : string ; @ Input ( ) cropperOptions : any = { } ; @ Output ( ) export = new EventEmitter < ImageCropperResult > ( ) ; @ Output ( ) ready = new EventEmitter ( ) ; public isLoading : boolean = true ; public cropper : Cropper ; public imageElement : HTMLImageElement ; public loadError : any ; constructor ( ) { } ngOnInit ( ) { } param ev imageLoaded ( ev ) { this . loadError = false ; const image = ev . target as HTMLImageElement ; this . imageElement = image ; if ( this . cropperOptions . checkCrossOrigin ) image . crossOrigin = 'anonymous' ; image . addEventListener ( 'ready' , ( ) => { this . ready . emit ( true ) ; this . isLoading = false ; if ( this . cropbox ) { this . cropper . setCropBoxData ( this . cropbox ) ; } } ) ; let aspectRatio = NaN ; if ( this . settings ) { const { width , height } = this . settings ; aspectRatio = width / height ; } this . cropperOptions = Object . assign ( { aspectRatio , movable : false , scalable : false , zoomable : false , viewMode : 1 , checkCrossOrigin : true } , this . cropperOptions ) ; if ( this . cropper ) { this . cropper . destroy ( ) ; this . cropper = undefined ; } this . cropper = new Cropper ( image , this . cropperOptions ) ; } param event imageLoadError ( event ) { this . loadError = true ; this . isLoading = false ; } param base64 exportCanvas ( base64 ? ) { const imageData = this . cropper . getImageData ( ) ; const cropData = this . cropper . getCropBoxData ( ) ; const canvas = this . cropper . getCroppedCanvas ( ) ; const data = { imageData , cropData } ; const promise = new Promise ( resolve => { if ( base64 ) { return resolve ( { dataUrl : canvas . toDataURL ( 'image/png' ) } ) ; } canvas . toBlob ( blob => resolve ( { blob } ) ) ; } ) ; promise . then ( res => { this . export . emit ( Object . assign ( data , res ) ) ; } ) ; } }