0

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);
Idancn
  • 37
  • 6
  • Maybe gif/jpg images are 3 bytes per pixel. (no alpha byte) – Nican Jun 14 '13 at 15:34
  • I tried to change it from i+=4 to i+=3 but it's not helping. Thanks for the try though.. – Idancn Jun 14 '13 at 16:20
  • @Nican, canvas will always have RGBA buffer no matter the image source is. –  Jun 14 '13 at 21:18
  • I had this problem, and the reason was that I wrote outside the dimensions of the imagedata. No idea why this introduced skewness – might be an overflow bug. – blinry Feb 12 '17 at 00:01

2 Answers2

1

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);
MacroMan
  • 2,335
  • 1
  • 27
  • 36
0

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.

okcoker
  • 1,329
  • 9
  • 16
  • I am manipulating the pixels relative to it's existing value, this part is hidden under the if statement and i'm absolutely satisfied with the B&W result i get. the problem is the skewness distortion that occur for some of the images (all images i try are .JPG). – Idancn Jun 14 '13 at 16:27