Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return File from ngx-image-cropper to upload - Angular

I am using ngx-image-cropper to crop my image. I need to retrieve the cropped image from ngx-image-cropper to upload. However, I can't retrieve File object through this.

This is the code that I used to trigger when the user crop the image,

imageCropped(event: ImageCroppedEvent) {
    this.croppedImage = event.base64;
    this.cropperHeight = event.height;
    this.cropperWidth = event.width;
    this.croppedEvent =event.file;//This is how i tried to get file
}

When I am trying to upload the file it has some error. So it is better to provide a way to get file object from ngx-image-cropper

like image 312
nipun-kavishka Avatar asked Nov 27 '22 16:11

nipun-kavishka


2 Answers

The package includes the method base64ToFile

// Import the method:

import { ImageCroppedEvent, base64ToFile } from 'ngx-image-cropper';

.....
imageCropped(event: ImageCroppedEvent) {
    this.croppedImage = event.base64;
    let File = base64ToFile(this.croppedImage);
}

source: https://github.com/Mawi137/ngx-image-cropper/releases/tag/3.0.0

like image 157
mentamarindo Avatar answered Dec 06 '22 09:12

mentamarindo


To return the cropped image as a file instead of a base64 string, add the following:


import { ImageCroppedEvent, base64ToFile } from 'ngx-image-cropper';

  imageCropped(event: ImageCroppedEvent) {
    // Preview
    this.croppedImage = event.base64;

    const fileToReturn = this.base64ToFile(
      event.base64,
      this.data.imageChangedEvent.target.files[0].name,
    )

    return fileToReturn;
  }


  base64ToFile(data, filename) {

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

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

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

like image 27
Kelvin Menegasse Avatar answered Dec 06 '22 10:12

Kelvin Menegasse