Just as there is a formula for converting an image to grayscale, is there a formula for increasing the brightness of an image and decreasing it in the same level? I tried adding a value to each of the r, g and b pixels. It does increase the brightness but when I reduce the same value, I don't get my original value back.
var pixels = context.getImageData(...);
//loop over the pixel data and add a value
p[i] = p[i]+100;
p[i+1] = p[i+1]+100;
p[i+2] = p[i+2]+100;
This brightens the image. But when I reduce 100 from every pixel, I don't get my original image back.
I read around the web that there are certain formulas to calculate this properly. Can anyone explain it? And similarly for contrast and gamma?
UPDATE:
Thanks all for the suggestions. I tried this after going through some of the posts below.
For increasing brightness:
var pixels = context.getImageData(...);
//loop over the pixel data and add a value
p[i] = p[i]+100 < 255 ? p[i]+100 : 255;
p[i+1] = p[i+1]+100 < 255 ? p[i+1]+100 : 255;
p[i+2] = p[i+2]+100 < 255 ? p[i+2]+100 : 255;
And for reducing brightness:
var pixels = context.getImageData(...);
//loop over the pixel data and add a value
p[i] = p[i]-100 >= 0 ? p[i]-100 : 0;
p[i+1] = p[i+1]-100 >= 0 ? p[i+1]-100 : 0;
p[i+2] = p[i+2]+100 >= 0 ? p[i+2]-100 : 0;
I can see the increment works fine, but when I decrement it, I still don't get the original image, there's a little difference between the original and brightened image!
What am I doing wrong?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…