Anderson Green
Anderson Green

Reputation: 31850

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.

Upvotes: 23

Views: 33894

Answers (1)

Simon Sarris
Simon Sarris

Reputation: 63872

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.

Upvotes: 22

Related Questions