4
votes

I'm using Angular (not AngularJS) and the ngx-img-cropper library. Once the image is cropped, is there a way to get the cropped jpg or png file? this.data.image inside of fileChangeListener($event) is a base64 image string 'data:image/png;base64,iVBORw0KGgo...'. this.cropper.image[0] is an HTML Element object and this.cropper.image[1] is a base 64 image string.

This is the ngx-img-cropper website https://github.com/web-dave/ngx-img-cropper. I'm trying to upload an image inside of fileChangeListener() about 3/4 of the way down the page.

1

1 Answers

3
votes

This is what worked for me. Installed file-saver using 'npm install file-saver --save'.

import { saveAs } from 'file-saver';

fileChangeListener($event) {
  const image: any = new Image();
  const file: File = $event.target.files[0];

  const myReader: FileReader = new FileReader();
  const that = this;
  myReader.onloadend = function (loadEvent: any) {
    image.src = loadEvent.target.result;
    that.cropper.setImage(image);
  };
  myReader.readAsDataURL(file);
  const base64: string = Object.values(that.cropper.image)[1];
  const blob = this.dataURItoBlob(base64);
  saveAs(blob, 'croppedFilezz.png');
}

dataURItoBlob(dataURI) {
  const binary = atob(dataURI.split(',')[1]);
  const array = [];
  for (let i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], {
    type: 'image/png'
  });
}

Where I got stuck: in the html don't forget #cropper inside of Credit to answer from @vava720 Convert Data URI to File then append to FormData