Contrast

This algorithm adjusts the contrast of specified image in RGB color space. This algorithm works by increasing RGB values of bright pixels and decreasing RGB values of dark pixels.

   



									public static void ApplyContrast(ref Bitmap bmp, sbyte contrastValue)
{
	if (contrastValue < -100 || contrastValue > 100) return;

	BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

	unsafe
	{
		byte* ptr = (byte*)bmpData.Scan0.ToPointer();

		int stopAddress = (int)ptr + bmpData.Stride * bmpData.Height;

		double pixel = 0, contrast = (100.0 + contrastValue) / 100.0;

		contrast *= contrast;

		while ((int)ptr != stopAddress)
		{
			pixel = ptr[0] / 255.0;
			pixel -= 0.5;
			pixel *= contrast;
			pixel += 0.5;
			pixel *= 255;
			if (pixel < 0) pixel = 0;
			else if (pixel > 255) pixel = 255;
			ptr[0] = (byte)pixel;

			pixel = ptr[1] / 255.0;
			pixel -= 0.5;
			pixel *= contrast;
			pixel += 0.5;
			pixel *= 255;
			if (pixel < 0) pixel = 0;
			else if (pixel > 255) pixel = 255;
			ptr[1] = (byte)pixel;

			pixel = ptr[2] / 255.0;
			pixel -= 0.5;
			pixel *= contrast;
			pixel += 0.5;
			pixel *= 255;
			if (pixel < 0) pixel = 0;
			else if (pixel > 255) pixel = 255;
			ptr[2] = (byte)pixel;

			ptr += 3;
		}
	}

	bmp.UnlockBits(bmpData);
}
								


Example

									Bitmap b = (Bitmap)Image.FromFile("rose.jpg");
ApplyContrast(ref b, 30);