javascript 使用 putImageData 从画布上的像素阵列绘制图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15908179/
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
Draw image from pixel array on canvas with putImageData
提问by Elias Pedersen
I am working on a project that can encrypt an image and redraw the decrypted image on canvas. As I am still pretty new to coding and programming, I am currently having issues redrawing the decrypted image data, which is a pixel array in the form R,G,B,A. I thought this would be possible by simply putting the data into
我正在开发一个可以加密图像并在画布上重绘解密图像的项目。由于我对编码和编程仍然很陌生,因此我目前在重绘解密的图像数据时遇到问题,该数据是 R、G、B、A 形式的像素阵列。我认为只需将数据放入
ctx.putImageData(imgd,0,0);
But firebug tells me that the value does not implement the interface for imagedata. I have posted the entire array here. The image is 160px wide and 120px high.
但是firebug 告诉我该值没有实现imagedata 的接口。我已经在这里发布了整个数组。图像宽 160 像素,高 120 像素。
Is there any way to reformat the array so that it is drawable on the canvas?
有什么方法可以重新格式化数组,使其可以在画布上绘制?
回答by Trevor
Using Uint8 you can this much quicker:
使用 Uint8 你可以更快:
var canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d"),
img = [27,32,26,28, ... ];
// Get a pointer to the current location in the image.
var palette = ctx.getImageData(0,0,160,120); //x,y,w,h
// Wrap your array as a Uint8ClampedArray
palette.data.set(new Uint8ClampedArray(img)); // assuming values 0..255, RGBA, pre-mult.
// Repost the data.
ctx.putImageData(palette,0,0);
No need to go byte-by-byte unless you need to modify the values first.
除非您需要先修改值,否则无需逐字节进行。
回答by Bart
Assuming imgd
is simply an Array containing all byte values, you still need to convert the array to ImageData.
假设imgd
只是一个包含所有字节值的数组,您仍然需要将数组转换为 ImageData。
var imgd = [27,32,26,28,33,27,30,35,29,31.....]
// first, create a new ImageData to contain our pixels
var imgData = ctx.createImageData(160, 120); // width x height
var data = imgData.data;
// copy img byte-per-byte into our ImageData
for (var i = 0, len = 160 * 120 * 4; i < len; i++) {
data[i] = imgd[i];
}
// now we can draw our imagedata onto the canvas
ctx.putImageData(imgData, 0, 0);