23

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.

3

1 Answer 1

22

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.

Sign up to request clarification or add additional context in comments.

5 Comments

What should the parameter type of "img" be? Should it be an image object, or should it be the image URL as a string?
@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,...."
I do not have <canvas/>, since I'm running a subset of XHTML, but I have <img/> How can I do that?
Would imgData be considered a byte array?
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];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.