我有一个名为 frameBytes
的 Uint8Array。我使用以下代码从该字节数组创建了 RGBA 值:
for (var i = 0; i < frameBytes.length; i++) {
imgData.data[4 * i] = frameBytes[i];// red
imgData.data[4 * i + 1] = frameBytes[i]; // green
imgData.data[4 * i + 2] = frameBytes[i];// blue
imgData.data[4 * i + 3] = 255; // alpha
}
然后我使用以下代码将 RGBA 值显示到 Canvas :
var ctx = fingerFrame.getContext('2d');
var imgData = ctx.createImageData(fingerFrame.width, fingerFrame.height);
ctx.putImageData(imgData, 0, 0, 0, 0, fingerFrame.width, fingerFrame.height);
之后,在 Canvas 上,我用它将图像放入图像标签中:
const img = document.getElementById('i');
img.src = fingerFrame.toDataURL();
但我不想使用 Canvas 。我想直接显示 Uint8Array 中图像标签中的图像。我怎样才能做到这一点?
最佳答案
I want to show image in image tag from Uint8Array directly
使用 Blob 非常简单:
// Small red dot image
const content = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 5, 0, 0, 0, 5, 8, 6, 0, 0, 0, 141, 111, 38, 229, 0, 0, 0, 28, 73, 68, 65, 84, 8, 215, 99, 248, 255, 255, 63, 195, 127, 6, 32, 5, 195, 32, 18, 132, 208, 49, 241, 130, 88, 205, 4, 0, 14, 245, 53, 203, 209, 142, 14, 31, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]);
document.getElementById('my-img').src = URL.createObjectURL(
new Blob([content.buffer], { type: 'image/png' } /* (1) */)
);
Should display a small red dot: <img id="my-img">
(1) 它也可以在不指定 Blob MIME 类型的情况下工作。
关于javascript - JavaScript 中 Uint8Array 到图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50620821/