21

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.

Community
  • 1
  • 1
Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • If you click on the link of the answer to that question it takes you to a detailed answer of how to invert the color of each pixel in an image. It should be trivial to convert that code into storing an array of pixels. – JaredMcAteer May 06 '12 at 19:30
  • 2
    See https://developer.mozilla.org/en/Canvas_tutorial – Rob W May 06 '12 at 19:30
  • possible duplicate of [how to get the RGB value of an image in a page using javascript?](http://stackoverflow.com/questions/2754865/how-to-get-the-rgb-value-of-an-image-in-a-page-using-javascript) – John Carter May 07 '12 at 01:13

1 Answers1

21

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.

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
  • 2
    What should the parameter type of "img" be? Should it be an image object, or should it be the image URL as a string? – Anderson Green May 07 '12 at 19:29
  • 2
    @AndersonGreen an instance of Image object, you can get it via either DOM, make a new one by: `var img = new Image(); img.src = "http://..." or img.src = "data:image/jpeg;base64,...."` – Mustafa Apr 01 '13 at 20:08
  • I do not have , since I'm running a subset of XHTML, but I have How can I do that? – loretoparisi Oct 26 '15 at 14:25
  • Would imgData be considered a byte array? – 1.21 gigawatts Dec 30 '15 at 03:13
  • Just a note that I had to initialise the width and height for both the image and the canvas to make it work: `let image = new Image(800,600); [canvas.width, canvas.height] = [img.width, img.height];` – Fappaz Sep 14 '20 at 05:08