Archive for January 23rd, 2008
c# Adjusting brightness,contrast, and gamma of an image.
by brian on Jan.23, 2008, under .NET, GUI, c#, c# coding GUI, coding, graphics
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 preforming a translate on the color data, and contrast is preforming a scale on the color. Gamma is a whole different form of transform, but it’s included in ImageAttributes which accepts the ColorMatrix.
So here’s the simple code:
Bitmap origanalImage;
Bitmap adjustedImage;
double brightness = 1.0f; // no change in brightness
double constrast = 2.0f; // twice the contrast
double 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 = 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,bitImage.Width,bitImage.Height,
GraphicsUnit.Pixel, imageAttributes);
So there it is. Simple enough isn’t it.
