gpt4 book ai didi

javascript - DOM异常: The source image could not be decoded

转载 作者:行者123 更新时间:2023-12-02 21:01:22 30 4
gpt4 key购买 nike

下面的方法抛出DOMException:源图像无法解码。的原因可能是什么?

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();
}
}

上面的代码在网络 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> 中标签,您的浏览器可能会更明确地说明问题所在。

关于javascript - DOM异常: The source image could not be decoded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61345388/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com