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 Shared Sub ApplyContrast(ByRef bmp As Bitmap, contrastValue As SByte)
	If contrastValue < -100 OrElse contrastValue > 100 Then
		Return
	End If

	Dim bmpData As BitmapData = bmp.LockBits(New Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb)
	Dim ptr As IntPtr = bmpData.Scan0
	Dim stopAddress As Integer = CInt(ptr) + bmpData.Stride * bmpData.Height
	Dim pixel As Double = 0, contrast As Double = (100.0 + contrastValue) / 100.0

	contrast *= contrast

	While CInt(ptr) <> stopAddress
		pixel = Marshal.ReadByte(ptr) / 255.0
		pixel -= 0.5
		pixel *= contrast
		pixel += 0.5
		pixel *= 255
		If pixel < 0 Then
			pixel = 0
		ElseIf pixel > 255 Then
			pixel = 255
		End If
		Marshal.WriteByte(ptr, CByte(Math.Truncate(pixel)))

		pixel = Marshal.ReadByte(ptr + 1) / 255.0
		pixel -= 0.5
		pixel *= contrast
		pixel += 0.5
		pixel *= 255
		If pixel < 0 Then
			pixel = 0
		ElseIf pixel > 255 Then
			pixel = 255
		End If
		Marshal.WriteByte(ptr + 1, CByte(Math.Truncate(pixel)))

		pixel = Marshal.ReadByte(ptr + 2) / 255.0
		pixel -= 0.5
		pixel *= contrast
		pixel += 0.5
		pixel *= 255
		If pixel < 0 Then
			pixel = 0
		ElseIf pixel > 255 Then
			pixel = 255
		End If
		Marshal.WriteByte(ptr + 2, CByte(Math.Truncate(pixel)))

		ptr += 3
	End While

	bmp.UnlockBits(bmpData)
End Sub
								


Example

									DIm b As Bitmap = CType(Image.FromFile("rose.jpg"), Bitmap)
ApplyContrast(b, 30)