Skip to content Skip to sidebar Skip to footer

How To Get The Croped Image Using Croppr.js?

I'm working on an Ionic 3 mobile application. In there I'm using Croppr.js library to crop the images before uploading to the server. But I couldn't find a way to get the cropped i

Solution 1:

If you are using ionic 3, then you can use @ionic-native/crop": "^4.7.0" plugin for image crop. I have used this plugin for image crop in ionic 3.

I have also used image cropping functionality in angular using "ng2-img-cropper" plugin. Refer below code which is used in angular project this will help you.
demo.ts :
import {ImageCropperComponent, CropperSettings, Bounds} from 'ng2-img-cropper';

 @ViewChild('cropper', undefined)
    cropper:ImageCropperComponent;  

constructor( private cropperSettings: CropperSettings ) {
        this.cropperSettings = new CropperSettings();
        this.cropperSettings.noFileInput = true;
    }

  // To browse image 
   fileChangeListener($event) {
        var image:any = new Image();
        var file:File = $event.target.files[0];
        var myReader:FileReader = new FileReader();
        var that = this;
        this.isfileOpen = true;
        myReader.onloadend = function (loadEvent:any) {
            image.src = loadEvent.target.result;
            that.cropper.setImage(image);
        };
        myReader.readAsDataURL(file);
    }

  //convert cropped base64 image to image
     var base64Blob = this.dataURItoBlob( file );

   /**
     * Function to convert base64 image 
    **/
    dataURItoBlob = ( dataURI ) => {
        var binary = atob( dataURI.split( ',' )[1] );
        var array = [];
        for ( var i = 0; i < binary.length; i++ ) {
            array.push( binary.charCodeAt( i ) );
        }
        return new Blob( [new Uint8Array( array )], { type: 'image/jpeg' } );
    }

demo.html :
<img-cropper #cropper [hidden]="!isfileOpen" [image]="data" [settings]="cropperSettings"></img-cropper> 
       <br>
       <div class="file-upload"  *ngIf="!isfileOpen">
         <input id="custom-input" accept="image/*" class="textCenter" type="file" (change)="fileChangeListener($event)">
       </div>

Solution 2:

Found a solution.

onCropEnd(data: { x: number, y: number, width: number, height: number }): void {
    console.log("On Crop End: ", data);

    const canvas = <HTMLCanvasElement>document.getElementById('myCanvas'),
      context = canvas.getContext('2d');
    const image = new Image()

    canvas.width = data.width;
    canvas.height = data.height;
    const loadedImg = <HTMLImageElement>document.getElementsByTagName('img')[0]
    image.src = loadedImg.src;

    context.drawImage(image, data.x, data.y, data.width, data.height, 0, 0, canvas.width, canvas.height);
    const dataUrl = canvas.toDataURL('image/jpeg');

    console.log("data url", dataUrl)
  }

Post a Comment for "How To Get The Croped Image Using Croppr.js?"