【问题标题】:Convert ImageBitmap to Blob将 ImageBitmap 转换为 Blob
【发布时间】:2019-03-28 07:53:07
【问题描述】:

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

如何将此文件转换为 blob 或最好的 PNG 格式以便上传?

【问题讨论】:

  • 我对我的答案进行了编辑,以使其使用位图渲染器上下文。在第一个版本中没有提及它是愚蠢的......

标签: javascript image html5-canvas


【解决方案1】:

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

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

重要说明关于位图渲染器的使用:
虽然这确实是最佳实践,Chrome currently has a bug 会导致输出图像是透明的,从而迫使我们改用 2d 上下文。
我保留了使用 bitmaprenderer 上下文的代码,但希望这个 bug 能很快得到修复,但这意味着下面的 sn-p 暂时只能在 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);
  });

检查HTMLCanvasElement#toBlob() 了解您可以传入的选项(文件格式和质量,如果适用)。

【讨论】:

  • 这确实有帮助,但由于某种原因,我得到了一个空图像。我已将其放入一个新问题stackoverflow.com/questions/52960102/…
  • 作为参考,我相信这已经在 Chrome 中修复了。
猜你喜欢
  • 2013-09-10
  • 2020-06-15
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 2021-05-25
  • 2015-02-17
相关资源
最近更新 更多