DOMException:无法解码源图像

DOMException: The source image could not be decoded

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

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 worker 中运行,特别是在解码过程之后:

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

嗯,损坏的图像会导致这种情况。

// 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> 标记中,您的浏览器可能更明确地说明问题是什么。

我遇到过类似的问题,我尝试从 api.

加载图像 url

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