首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DOMException:无法解码源图像

DOMException:无法解码源图像
EN

Stack Overflow用户
提问于 2020-04-21 13:59:30
回答 2查看 5.9K关注 0票数 1

下面的方法抛出DOMException: The source image could not be decoded.的原因是什么?

代码语言:javascript
复制
async function drawImage(blob) {
    console.log('Start draw image.')
    console.log(blob);
    if(context === undefined) {
        console.log('Context is not defined.');
    } else if(blob.type === 'image/jpeg') {
        console.log('Drawing image');
        // Error: DOMException: The source image could not be decoded.
        const bmp = await createImageBitmap(blob);
        context.drawImage(bmp, 0, 0);
        bmp.close();
    }
}

上面的代码在web工作者内部运行,特别是在解码过程之后:

代码语言:javascript
复制
onmessage = async function (e) {
    let jpegBlob = decodeBinary(e.data);
    drawImage(jpegBlob);
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-04-22 02:31:37

一个破碎的图像就会导致这一切。

代码语言:javascript
复制
// The same would happen in a Worker thread,
// it's just easier for StackSnippet to log from main thread
const context = document.createElement('canvas').getContext('2d');

function decodeBinary() {
  return new Blob(["not an image"], {type: 'image/jpeg'});
}
async function drawImage(blob) {
  console.log('Start draw image.')
  console.log(blob);
  if (context === undefined) { // beware, unsupported call to getContext returns `null`, not `undefined`
    console.log('Context is not defined.');
  } else if (blob.type === 'image/jpeg') {
    console.log('Drawing image');
    // Error: DOMException: The source image could not be decoded.
    const bmp = await createImageBitmap(blob);
    context.drawImage(bmp, 0, 0);
    bmp.close();
  }
}

onmessage = async function(e) {
  let jpegBlob = decodeBinary(e.data);
  drawImage(jpegBlob).catch(console.error);
}

self.postMessage('', '*');

因此,您需要检查Blob的内容,并调试decodeBinary函数。

作为第一步,您可以检查文件签名是否与JPEG图像之一匹配:

new Uint8Array( (await blob.slice(0,3).arrayBuffer()) ).join("") === "255216255";

您还可以尝试将该Blob传递给您的主线程,从它创建一个blob: URL,并尝试将其加载到<img>标记中,您的浏览器可能会更清楚地了解问题所在。

票数 1
EN

Stack Overflow用户

发布于 2021-05-07 09:05:00

我遇到了一个类似的问题,我试图从一个api加载一个图像url。

我在url的开头添加了http://,我的问题就解决了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61345388

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档