'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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1