javascript 如何从 jpeg 或 png 格式的字节数组在画布上绘制图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21434167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Draw an image on canvas from a byte array in jpeg or png format
提问by Ben
Like the title says, I have a byte array representing the contents of an image (can be jpeg or png).
正如标题所说,我有一个字节数组表示图像的内容(可以是 jpeg 或 png)。
I want to draw that on a regular canvas object
我想把它画在一个普通的画布对象上
<canvas id='thecanvas'></canvas>
How can I do that?
我怎样才能做到这一点?
UPDATEI tried this (unsuccesfully): (imgData is a png sent as a byte array "as is" through WebSockify to the client)
更新我试过这个(不成功):(imgData 是一个 png 作为字节数组“按原样”通过 WebSockify 发送到客户端)
function draw(imgData) {
"use strict";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var rdr = new FileReader();
var imgBlob = new Blob([imgData], {type: "image/png"});
rdr.readAsBinaryString(imgBlob);
rdr.onload = function (data) {
console.log("Filereader success");
var img = new Image();
img.onload = function () {
console.log("Image Onload");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
img.onerror = function (stuff) {
console.log("Img Onerror:", stuff);
};
img.src = "data:image/png;base64," + window.btoa(rdr.result);
};
}
I always reach img.onerror()
我总是达到 img.onerror()
AlsoAfter reading the file with a HEX editor on my file system, I can see that the byte array is identical to the original file.
此外,在我的文件系统上使用 HEX 编辑器读取文件后,我可以看到字节数组与原始文件相同。
回答by Ben
This Works:
这个作品:
function draw2(imgData, coords) {
"use strict";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
//var uInt8Array = new Uint8Array(imgData);
var uInt8Array = imgData;
var i = uInt8Array.length;
var binaryString = [i];
while (i--) {
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
var base64 = window.btoa(data);
var img = new Image();
img.src = "data:image/png;base64," + base64;
img.onload = function () {
console.log("Image Onload");
ctx.drawImage(img, coords[0], coords[1], canvas.width, canvas.height);
};
img.onerror = function (stuff) {
console.log("Img Onerror:", stuff);
};
}