How do I access / change pixels in a javascript image object?

I am drawing an image to canvas for display on a web page. I have two copies of the image. The first is the original or ground truth, and the second is a copy that will apply various image processing algorithms.

How can I copy pixels from a ground rights image to a copy and how can I access the pixels in a copy to process the image after copying it?

The examples I've seen so far involve accessing and manipulating the canvas object, not image data. Is this the recommended solution? Draw your original image onto canvas and then process the canvas?

+3


source to share


1 answer


To get the image data, use the getImageData () method of the canvas context and then access the pixel data from the data property. Each pixel in the data property contains a red, green, blue, and alpha channel. So, if you painted your image on a canvas, you could do

var imageData = context.getImageData(imageX, imageY, imageWidth, imageHeight);
var data = imageData.data;

      

Then you could select specific pixel data from x and y coordinates, for example



// pick out pixel data from x, y coordinate
var x = 20;
var y = 20;
var red = data[((imageWidth * y) + x) * 4];
var green = data[((imageWidth * y) + x) * 4 + 1];
var blue = data[((imageWidth * y) + x) * 4 + 2];
var alpha = data[((imageWidth * y) + x) * 4 + 3];

      

You can find more information on how to work with image data using the canvas on the right here .

Hope it helps.

+4


source







All Articles