Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ImageBitmap to Blob

I'm using createImageBitmap() which creates an ImageBitmap file.

How do I convert this file to a blob or ideally PNG so I can upload?

like image 535
beek Avatar asked Mar 06 '23 05:03

beek


1 Answers

The only way currently is to draw it on a canvas.

For more efficiency, you can try to use an ImageBitmapRenderingContext, which will not copy the pixels buffer again.

(async () => {

  const resp = await fetch('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png');
  // yes.. from a Blob to a Blob...
  const blob1 = await resp.blob();
  const bmp = await createImageBitmap(blob1);
  console.log(bmp); // ImageBitmap
  // create a canvas
  const canvas = document.createElement('canvas');
  // resize it to the size of our ImageBitmap
  canvas.width = bmp.width;
  canvas.height = bmp.height;
  // get a bitmaprenderer context
  const ctx = canvas.getContext('bitmaprenderer');
  ctx.transferFromImageBitmap(bmp);
  // get it back as a Blob
  const blob2 = await new Promise((res) => canvas.toBlob(res));
  console.log(blob2); // Blob
  const img = document.body.appendChild(new Image());
  img.src = URL.createObjectURL(blob2);
  
})().catch(console.error);

Check HTMLCanvasElement#toBlob() for the options you can pass in (file format and quality when applicable).

like image 139
Kaiido Avatar answered Mar 16 '23 22:03

Kaiido