Question

I'm a little stuck trying to get the pixel color of an image. I need to get the RGB value of a pixel, jump three and store it in an array, but my console always returns [0, 0, 0...].

You have any idea how to do this in a better way?

My code looks like this:

function captureImageData( image )
{
    var cnv = document.createElement( 'canvas' );
    cnv.width = image.width;
    cnv.height = image.height;

    var ctx = cnv.getContext( '2d' );
    ctx.drawImage( image, 0, 0 );

    var imageData = ctx.getImageData( 0, 0, 200, 100 );

    var data = imageData.data;
    var height = imageData.height;
    var width = imageData.width;

    for ( var y = 0; y < 100; y += 2 ) 
    {
        for ( var x = 0; x < 200; x += 2 ) 
        {
            red.push(data[( y * imageData.width + x ) * 4 + 0]);
            green.push(data[( y * imageData.width + x ) * 4 + 1]);
            blue.push(data[( y * imageData.width + x ) * 4 + 2]);
            alpha.push(data[( y * imageData.width + x ) * 4 + 3]);
        }
    }

    console.log( red );
}
Was it helpful?

Solution

How are you passing the image to the function? Try the following, it works fine for me.

Live Demo

var red = [],
    green = [],
    blue = [],
    alpha = [];

function captureImageData(image) {
    var cnv = document.createElement('canvas');
    cnv.width = image.width;
    cnv.height = image.height;

    var ctx = cnv.getContext('2d');
    ctx.drawImage(image, 0, 0);

    var imageData = ctx.getImageData(0, 0, 200, 100);

    var data = imageData.data;
    var height = imageData.height;
    var width = imageData.width;
    var index = 0;

    for (var y = 0; y < 100; y += 2) {
        for (var x = 0; x < 200; x += 2) {
            index = (y * imageData.width + x) * 4;
            red.push(data[index]);
            green.push(data[index + 1]);
            blue.push(data[index + 2]);
            alpha.push(data[index + 3]);
        }
    }
    // log out any pixel here
    console.log(red[1]);
}

var image = new Image();

image.crossOrigin = true;
image.src = "http://i.imgur.com/LdmrhlK.jpg";

image.onload = function () {
    captureImageData(this);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top