0

I am trying to build something like this or this. In order to reduce the filesize I want to separate on colorchannel and then grayscale it, similar to the channel separate command in Imagick convert rose: -channel R -separate separate_red.gif

So my code looks like this

var imageData = ctx.getImageData(0,0,cw, ch);
  var data= imageData.data

    for (var i = 0; i < data.length; i += 4) {

      data[i]     = 0; // red
      data[i + 2] = 0; // blue

    }

    for (var i = 0; i < data.length; i += 4) {
      var grayscale = data[i]*0.2126 + data[i +1]*0.7152 + data[i +2]*0.0722;
      data[i]     = grayscale; // red
      data[i + 1] = grayscale; // green
      data[i + 2] = grayscale; // blue

    }

    ctx.putImageData(imageData, 0, 0);
}

with the first for loop I am grabbing the green color channel and then in the second I grayscale it.

That works for png with transparent background, however if they have white background they turn into a dark grey. How do I turn that off? IS there something wrong with the alphachannel?

Thanks in advance

Tom
  • 2,545
  • 5
  • 31
  • 71
  • First loop is pointless. simply don't add data[i] & data[i + 2] to your grayscale formula – Amit Aug 26 '15 at 21:56
  • So you mean like this `for (var i = 0; i < data.length; i += 4) { var grayscale = data[i]*0.2126 + data[i +1]*0.7152 + data[i +2]*0.0722; data[i + 1] = grayscale; // green }` ? Cause that will give me picture that is more blue than gray – Tom Aug 26 '15 at 22:14
  • What I meant was that you don't need the first loop at all in order to calculate your `grayscale` value (not referring to the "correctness" of this value, just the way it's calculated). You could simply do `grayscale = data[i + 1] * 0.7152`. Regarding the calculation part, you might want to look [here](http://stackoverflow.com/a/689547/3887516) – Amit Aug 26 '15 at 22:17
  • Ok, I don't get it, if I do this `for (var i = 0; i < data.length; i += 4) { var grayscale = data[i +1]*0.7152; data[i] = grayscale; data[i + 1] = grayscale; data[i + 2] = grayscale; }` the white background is still grey, should I go over it with a second loop and turn everything that is pure grey (182,182,182) back into white (255,255,255)? – Tom Aug 26 '15 at 22:38

1 Answers1

1

Consider a fully opaque white pixel in your source image. It will have the values:

R = 255
G = 255
B = 255
A = 255

If you truncate R & B to 0, and then use 0.7152 of G to set each of the channels back, you get:

R = 182
G = 182
B = 182
A = 255

And that's a grey color.

If you want it white, you need different logic.

Amit
  • 45,440
  • 9
  • 78
  • 110