【问题标题】:createImageBitmap returns an empty imagecreateImageBitmap 返回一个空图像
【发布时间】:2018-10-24 10:40:50
【问题描述】:

我正在使用 createImageBitmap 在工作人员中转换图像。

进入的 blob 有数据,定位有效(它们是负数,但我尝试使用 0 和相同的问题)

 createImageBitmap(blob, -pos.x + 100, -pos.y + 100, 200, 200).then(data => {
            resolve(data)})

出来的数据是<ImageData width: 200, height 200 />

然后尝试将其转换为 blob

const canvas = document.createElement('canvas')
      canvas.height = img.height
      canvas.width = img.width
      const context = canvas.getContext('bitmaprenderer')
      context.transferFromImageBitmap(img)

canvas.toBlob((blob)=> ..

blob 是空的。

关于我哪里出错的任何线索?

【问题讨论】:

  • 它们可以是零。第一个 blob 来自 aframe (webGL) 中生成的大图像,我将它传递给工作人员进行图像处理和调整大小,因为它已经冻结了浏览器。第一个 blob 是有效的,带有数据。它将日志控制台显示为具有大量数据。我试过 pos.x 和 y = 0 并没有区别。

标签: javascript image


【解决方案1】:

这是一个带有位图渲染器上下文的Chrome bug...

无论出于何种原因,HTMLCanvasElement.toBlob()HTMLCanvasElement.toDataURL() 的结果将是完全透明的图像...

它们不遵守 HTMLCanvasElement 中显示的当前活动位图缓冲区。

这可以通过将画布附加到文档来演示:

fetch('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png')
  .then(r => r.blob())
  .then(b=>createImageBitmap(b, 120,120,120,120))
  .then(img => {
    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;
      document.body.append(canvas);
      // transfer on the bitmarenderer context
      canvas.getContext('bitmaprenderer')
        .transferFromImageBitmap(img);
      // get it back as a Blob
      canvas.toBlob(res);
    });
  })
  .then(blob => {
    var img = document.body.appendChild(new Image());
    img.src = URL.createObjectURL(blob);
  });
img {
  border: solid red;
}
canvas {
  border: solid green;
}

您可以为the issue 加注星标,使其获得更高的优先级,并且暂时您可能希望回退到 2dContext 及其消耗内存的 drawImage() 方法...

fetch('https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png')
  .then(r => r.blob())
  .then(b=>createImageBitmap(b, 120,120,120,120))
  .then(img => {
    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;
      document.body.append(canvas);
      // draw on a 2d context
      canvas.getContext('2d')
        .drawImage(img,0,0);
      // get it back as a Blob
      canvas.toBlob(res);
    });
  })
  .then(blob => {
    var img = document.body.appendChild(new Image());
    img.src = URL.createObjectURL(blob);
  });
img {
  border: solid red;
}
canvas {
  border: solid green;
}

【讨论】:

  • 谢谢@Kaiido - 你很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 2014-06-18
  • 2014-03-27
  • 2012-06-03
  • 1970-01-01
相关资源
最近更新 更多