cstefanache / angular2-img-cropper

Angular 2 Image Cropper
MIT License
364 stars 135 forks source link

Support for blob #178

Open niravpatel9898 opened 7 years ago

niravpatel9898 commented 7 years ago

Does it have support for blob or is there a way in which the image can be converted to blob ?

zbarbuto commented 7 years ago

(from http://stackoverflow.com/questions/12168909/blob-from-dataurl, convert base64 image to blob for upload)

toFileObject(dataURI) {
    let byteString = atob(dataURI.split(',')[1]);
    // separate out the mime component
    let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to an ArrayBuffer
    let ab = new ArrayBuffer(byteString.length);
    let ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    let blob = new Blob([ab], {type: mimeString});
    return (<File> blob);
  }
}
alex-pl commented 7 years ago

I had the same problem and wanted the Blob for direct upload with FormData which might be way more performant than converting to base64 and back.

This is my current solution, but it's obviously a hack. Generally there's nothing wrong with it, but it uses internal code that might change any time.

// cropper definition
private cropper: ImageCropperComponent;

// helper method so I'm able to use async/await
private async getBlobFromCanvas(canvas: HTMLCanvasElement): Promise<Blob> {
    return new Promise<Blob>((resolve) => {
        canvas.toBlob(resolve);
    });
}

// get the image blob (you can use .then() instead of await)
let imageBlob = await this.getBlobFromCanvas(<HTMLCanvasElement>(<any>this.cropper.cropper).cropCanvas);

Would be great to have an official way to do this :).

eduardoturconi commented 6 years ago

+1 for exposing cropCanvas in an official and supported way. Currently this way works:

async getBlob() {
  const cropCanvas = <HTMLCanvasElement>(this.cropper.cropcanvas.nativeElement)
  return new Promise((resolve) => {
    cropCanvas.toBlob(resolve)
  })
}
web-dave commented 6 years ago

new name and new repo. I'll take care of this. https://www.npmjs.com/package/ngx-img-cropper

eduardoturconi commented 6 years ago

@web-dave

Thanks! But maybe expose the canvas isn't really necessary if the <img-cropper/>'s input [image] get some function like asBlob() that internally get the blob from canvas.