Ok, so earlier I talked about adjusting the brightness and the gamma of an image. So in this post I'm going to show you how to adjust the contrast of an image. Contrast deals with the visual properties that allows us to see two seperate objects as well as the background. We can measure the contrast of something by taking into account both the color and brightness. In otherwords if I have a green box inside of a green circle, there's basically no contrast. If you have a red box inside a blue circle, there is a higher contrast. So how do we go about and adjust the contrast
public static Bitmap AdjustContrast(Bitmap Image, float Value)
{
Value = (100.0f + Value) / 100.0f;
Value *= Value;
System.Drawing.Bitmap TempBitmap = Image;
System.Drawing.Bitmap NewBitmap = new System.Drawing.Bitmap(TempBitmap.Width, TempBitmap.Height);
System.Drawing.Graphics NewGraphics = System.Drawing.Graphics.FromImage(NewBitmap);
NewGraphics.DrawImage(TempBitmap, new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), System.Drawing.GraphicsUnit.Pixel);
NewGraphics.Dispose();
for (int x = 0; x < NewBitmap.Width; ++x)
{
for (int y = 0; y < NewBitmap.Height; ++y)
{
Color Pixel = NewBitmap.GetPixel(x, y);
float Red = Pixel.R / 255.0f;
float Green = Pixel.G / 255.0f;
float Blue = Pixel.B / 255.0f;
Red = (((Red - 0.5f) * Value) + 0.5f) * 255.0f;
Green = (((Green - 0.5f) * Value) + 0.5f) * 255.0f;
Blue = (((Blue - 0.5f) * Value) + 0.5f) * 255.0f;
NewBitmap.SetPixel(x, y, Color.FromArgb(Clamp((int)Red, 255, 0), Clamp((int)Green, 255, 0), Clamp((int)Blue, 255, 0)));
}
}
return NewBitmap;
}
If you take a look at the code, you'll notice that I start by normalizing the values from 0.0 to 1.0 (with Value ending up going from 0 to 4 once normalized). Once a pixel is normalized, we multiply it by the value and then convert it back to the 0 to 255 range. That's pretty much it. The function takes in a bitmap and a value between -100 and 100 (you can use a different range but that will work the best) with a higher number causing more contrast and negative numbers decreasing it. Anyway, definitely try it out, leave feedback, and happy coding.
249f90f8-77c4-4173-ad6b-4b6686e67539|3|3.7