What is an easy way to adjust brightness contrast and gamma of an Image in .NET
Will post the answer myself to find it later.
Contrast is like brightness, except it makes all the pixels that are brigher than 50% brigther, and all pixels that are darker than 50% darker. Again, details are lost. Gamma only affects pixels in the midrange, but as you get closer to the brighter or darker parts of the image, it makes les and less of a change.
Increasing the brightness to make the image overall brighter, and decreasing will make it darker. Contrast works by adjusting the bright and dark parts of an image in relation to each other. When the Contrast is decreased, the image becomes grayer and the colors are less sharp.
You can adjust the gamma value by changing the LCD monitor's brightness settings or by adjusting brightness in the driver menu for the graphics card. Naturally, it's even easier to adjust the gamma if you use a model designed for gamma value adjustments, like an EIZO LCD monitor.
c# and gdi+ have a simple way to control the colors that are drawn. It’s basically a ColorMatrix. It’s a 5×5 matrix that is applied to each color if it is set. Adjusting brightness is just performing a translate on the color data, and contrast is performing a scale on the color. Gamma is a whole different form of transform, but it’s included in ImageAttributes which accepts the ColorMatrix.
Bitmap originalImage;
Bitmap adjustedImage;
float brightness = 1.0f; // no change in brightness
float contrast = 2.0f; // twice the contrast
float gamma = 1.0f; // no change in gamma
float adjustedBrightness = brightness - 1.0f;
// create matrix that will brighten and contrast the image
float[][] ptsArray ={
new float[] {contrast, 0, 0, 0, 0}, // scale red
new float[] {0, contrast, 0, 0, 0}, // scale green
new float[] {0, 0, contrast, 0, 0}, // scale blue
new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha
new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}};
ImageAttributes imageAttributes = new ImageAttributes();
imageAttributes.ClearColorMatrix();
imageAttributes.SetColorMatrix(new ColorMatrix(ptsArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
imageAttributes.SetGamma(gamma, ColorAdjustType.Bitmap);
Graphics g = Graphics.FromImage(adjustedImage);
g.DrawImage(originalImage, new Rectangle(0,0,adjustedImage.Width,adjustedImage.Height)
,0,0,originalImage.Width,originalImage.Height,
GraphicsUnit.Pixel, imageAttributes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With