将 ImageBitmap 转换为 Blob

bee*_*eek 2 javascript image html5-canvas

我正在使用 createImageBitmap() 创建一个ImageBitmap文件。

如何将此文件转换为 blob 或理想情况下的 PNG,以便我可以上传?

Kai*_*ido 6

目前唯一的方法是在画布上绘制它。

为了提高效率,您可以尝试使用ImageBitmapRenderingContext,它不会再次复制像素缓冲区。

关于使用位图渲染器的重要说明
虽然这确实是最佳实践,但Chrome 当前存在一个错误该错误会导致输出图像透明,从而迫使我们改用 2d 上下文。
我使用 bitmaprenderer 上下文保留代码,但希望此错误能尽快得到修复,但这意味着以下代码段暂时仅适用于 FF。

fetch('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png')
  .then(r => r.blob()) // yes.. from a Blob to a Blob...
// ImageBitmap generation  
  .then(createImageBitmap)
// to Blob
  .then(img => {
    console.log(img); // ImageBitmap
    return new Promise(res => {
      // create a canvas
      const canvas = document.createElement('canvas');
      // resize it to the size of our ImageBitmap
      canvas.width = img.width;
      canvas.height = img.height;
      // try to get a bitmaprenderer context
      let ctx = canvas.getContext('bitmaprenderer');
      if(ctx) {
        // transfer the ImageBitmap to it
        ctx.transferFromImageBitmap(img);
      }
      else {
        // in case someone supports createImageBitmap only
        // twice in memory...
        canvas.getContext('2d').drawImage(img,0,0);
      }
      // get it back as a Blob
      canvas.toBlob(res);
    });
  })
  .then(blob => {
    console.log(blob); // Blob
    var img = document.body.appendChild(new Image());
    img.src = URL.createObjectURL(blob);
  });
Run Code Online (Sandbox Code Playgroud)

检查HTMLCanvasElement#toBlob()以获取您可以传入的选项(适用时的文件格式和质量)。