Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an image to an RGB array in Javascript

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.

UPDATE: I found an exact duplicate here: how to get the RGB value of an image in a page using javascript?

However, the answers don't go into much detail about how to actually solve this problem.

like image 549
Anderson Green Avatar asked May 06 '12 19:05

Anderson Green


1 Answers

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.

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.

like image 182
Simon Sarris Avatar answered Oct 16 '22 01:10

Simon Sarris