下面的方法抛出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工作者内部运行,特别是在解码过程之后:
onmessage = async function (e) {
let jpegBlob = decodeBinary(e.data);
drawImage(jpegBlob);
}发布于 2020-04-22 02:31:37
一个破碎的图像就会导致这一切。
// 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>标记中,您的浏览器可能会更清楚地了解问题所在。
发布于 2021-05-07 09:05:00
我遇到了一个类似的问题,我试图从一个api加载一个图像url。
我在url的开头添加了http://,我的问题就解决了。
https://stackoverflow.com/questions/61345388
复制相似问题