javascriptimagehtml5-canvasimagebitmap

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

  • 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);

    However transferring an ImageBitmap will internally close it and thus make it unusable later. If you need to use it again later, you could create a new ImageBitmap from it before transferring it (async but small footprint), or use either the bitmap renderer's canvas where you'd have used the bitmap (may not be practical in every case), so the easiest in that particular case might be to use a 2D context and drawImage which will keep the ImageBitmap "alive".

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