javascript 在Javascript中将图像转换为RGB数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10473484/
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
Convert an image to an RGB array in Javascript
提问by Anderson Green
Is it possible to get an array of pixels from a PNG or BMP image in Javascript? I'd like to obtain an RGB array from an image so that I can manipulate the array of pixels, and then draw the modified image on a canvas.
是否可以在 Javascript 中从 PNG 或 BMP 图像中获取像素数组?我想从图像中获取一个 RGB 数组,以便我可以操作像素数组,然后在画布上绘制修改后的图像。
UPDATE:I found an exact duplicate here: how to get the RGB value of an image in a page using javascript?
更新:我在这里找到了一个完全相同的副本:如何使用 javascript 获取页面中图像的 RGB 值?
However, the answers don't go into much detail about how to actually solve this problem.
但是,答案并未详细说明如何实际解决此问题。
采纳答案by Simon Sarris
There are a hundred tutorials on the net about using HTML Canvas imageData, which gets the RGBA values of an canvas. Do a search for canvas imageData and you'll find plenty of info.
网上有一百篇关于使用 HTML Canvas imageData 的教程,它获取画布的 RGBA 值。搜索canvas imageData,你会发现很多信息。
All you have to do is:
您所要做的就是:
ctx.drawImage(img, 0, 0);
var imgData = ctx.getImageData(x, y, width, height).data;
imgData is now an array where every 4 places are each pixel. So [0][1][2][3]
are the [r][g][b][a]
of the first pixel.
imgData 现在是一个数组,其中每 4 个位置是一个像素。因此[0][1][2][3]
是[r][g][b][a]
第一像素。