Idancn
Idancn

Reputation: 37

HTML5 canvas pixel manipulation with imageData

I'm trying to create some black and white copy of an image like this

for some pictures it works perfect and for some pictures i get this skewed result as you can see on the link.

this is my code:

var imageData = ctx.createImageData(c.width, c.height);

for (var i=0; i < imageData.data.length; i+=4) 
{
    if (someLogicRefferingToOriginalImageData == true) {
        imageData.data[i+0] = 255;
        imageData.data[i+1] = 255;
        imageData.data[i+2] = 255;
        imageData.data[i+3] = 255;
    }
    else 
    {
        imageData.data[i+0] = 0;
        imageData.data[i+1] = 0;
        imageData.data[i+2] = 0;
        imageData.data[i+3] = 255;
    }
}

ctx.putImageData(imageData,0 ,0);

Upvotes: 0

Views: 996

Answers (2)

MacroMan
MacroMan

Reputation: 2458

Looking at your code, it should work. Try working on a 32bit array instead, which is one array element per pixel instead of 4, which should avoid any errors with element miscounting:

var imageData = ctx.createImageData(c.width, c.height);
var buffer = new Uint32Array(imageData.data.buffer);

for (var i=0; i < buffer.length; i++) {
    if (someLogicRefferingToOriginalImageData == true) {
        buffer[i] = 0xFFFFFFFF;
    } else {
        buffer[i] = 0xFF000000;
    }
}

imageData.data.set(new Uint8ClampedArray(buffer));
ctx.putImageData(imageData, 0, 0);

Upvotes: 1

okcoker
okcoker

Reputation: 1339

You have the right idea in going through every pixel but you can't just make certain pixels white and certain pixels black.

Each pixel should be manipulated relative to it's existing value. There are formulas for certain filters including B&W. The luminance algorithm seems to be what you're looking for. Maybe this link here will point you in the right direction for Black and White specifically.

Upvotes: 0

Related Questions