bufferedimage brightness/contrast

So, I looked it up. The only way I found to do this was this:

RescaleOp rescaleOp = new RescaleOp(contrast, brightness, null);
buffImg = rescaleOp.filter(i, i);

Thing is, the contrast seems to account for BOTH. Making it entirely useless for what I need done.

Any way to actually change them separately without some api?

What do you mean the contrast accounts for “both” – both what? The “contrast” parameter is just a scale factor, i.e. the amount to scale each color by. The “brightness” is just an offset, i.e. the amount to add to each color after scaling. So in this case, “brightness” will appear OK, but “contrast” may not really represent true contrast adjustment since it’s just scaling the color.

To achieve a better contrast adjustment, you could simply loop through and use a simple algorithm like this: (untested…)

//this assumes TYPE_3BYTE_BGR

float contrast = 0.7f;
float brightness = -0.1f;

byte[] buf = ((DataBufferByte)src.getRaster().getDataBuffer()).getData();

//for each BGR color in "pixel"
for (int i=0; i<buf.length; i++) {
  float c = buf[i] / 255f;
  c = ((c - 0.5) * Math.max(0f, contrast)) + 0.5f
  c += brightness;
  buf[i] = Math.min(Math.max(255 * c, 0f), 1f);
}

Alternatively you could use some other (perhaps more accurate) algorithms:


http://www.kweii.com/site/color_theory/2007_LV/BrightnessCalculation.pdf

This would be very simple and efficient with OpenGL/GLSL. :slight_smile: The code looks like this – you can try pasting it into ShaderToy and hitting Alt + Enter to test it out.