angular2-img-cropper icon indicating copy to clipboard operation
angular2-img-cropper copied to clipboard

Support for blob

Open niravpatel9898 opened this issue 8 years ago • 5 comments

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

niravpatel9898 avatar Apr 11 '17 06:04 niravpatel9898

(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);
  }
}

zbarbuto avatar May 02 '17 11:05 zbarbuto

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 :).

alex-pl avatar Jun 16 '17 13:06 alex-pl

+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)
  })
}

eduardoturconi avatar Jan 31 '18 16:01 eduardoturconi

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

web-dave avatar Feb 09 '18 15:02 web-dave

@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.

eduardoturconi avatar Feb 09 '18 20:02 eduardoturconi