Color Substitution

This algorithm replaces the specified source color with the new color.

   



									Public Shared Sub ApplyColorSubstitution(ByRef bmp As Bitmap, threshold As Integer, sourceColor As System.Drawing.Color, newColor As System.Drawing.Color)
	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 SrcTotalRGB As Integer = sourceColor.R + sourceColor.G + sourceColor.B
	Dim TotalRGB As Integer

	While CInt(ptr) <> stopAddress
		TotalRGB = CInt(Marshal.ReadByte(ptr)) + CInt(Marshal.ReadByte(ptr + 1)) + CInt(Marshal.ReadByte(ptr + 2))

		If Math.Abs(SrcTotalRGB - TotalRGB) < threshold Then
			Marshal.WriteByte(ptr, newColor.B)
			Marshal.WriteByte(ptr + 1, newColor.G)
			Marshal.WriteByte(ptr + 2, newColor.R)
		End If

		ptr += 3
	End While

	bmp.UnlockBits(bmpData)
End Sub
								


Example

									DIm b As Bitmap = CType(Image.FromFile("rose.jpg"), Bitmap)
ApplyColorSubstitution(b, 50, Color.Green, Color.Blue)