ImageCroppedEvent not working for "ngx-image-cropper": "^7.1.1",

138 Views Asked by At

The original tutorial I was following tried to use event.base64ToFile on the ImageCroppedEvent. Which is deprecated now.

here is what I am trying to do now:

    imageCropped(event: ImageCroppedEvent) {
        //this.croppedImage = (event as ImageCroppedEvent).base64ToFile;
        this.croppedImage =  this.sanitizer.bypassSecurityTrustUrl(event.objectUrl);
    }

    onCrop() {
        const file = dataURLtoFile(this.croppedImage, this.imageFile.name);
        this.changed.emit(file);
    }

export const dataURLtoFile = (dataurl, filename): File => {

    const arr = dataurl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }

    return new File([u8arr], filename, { type: mime });
};

I get ERROR TypeError: dataurl.split is not a function as an error.I am not sure how to repalce .base64ToFile with anything that works with the rest of the code.

1

There are 1 best solutions below

1
On BEST ANSWER

The event.objectUrl is not a base64 string, it is a url representing the cropped image. To convert this URL to a base64 string, use fetch to get the image data and then convert it to a base64 string.

imageCropped(event: ImageCroppedEvent) {
   fetch(event.objectUrl)
       .then(response => response.blob())
       .then(blob => {
           const reader = new FileReader();
           reader.onloadend = () => {
               this.croppedImage = reader.result;
           };
           reader.readAsDataURL(blob);
       });
}

onCrop() {
   const file = dataURLtoFile(this.croppedImage, this.imageFile.name);
   this.changed.emit(file);
}

export const dataURLtoFile = (dataurl, filename): File => {
   const arr = dataurl.split(',');
   const mime = arr[0].match(/:(.*?);/)[1];
   const bstr = atob(arr[1]);
   let n = bstr.length;
   const u8arr = new Uint8Array(n);

   while (n--) {
       u8arr[n] = bstr.charCodeAt(n);
   }

   return new File([u8arr], filename, { type: mime });
};