你能在Bitmap图像中将一种颜色更改为另一种颜色吗?

对于Bitmap ,有一个MakeTransparent方法,有一个类似的用于将一种颜色更改为另一种颜色吗?

 // This sets Color.White to transparent Bitmap myBitmap = new Bitmap(sr.Stream); myBitmap.MakeTransparent(System.Drawing.Color.White); 

有什么东西可以做这样的事吗?

 Bitmap myBitmap = new Bitmap(sr.Stream); myBitmap.ChangeColor(System.Drawing.Color.Black, System.Drawing.Color.Gray); 

通过对Yorye Nathan的评论的好奇,这是我通过修改http://msdn.microsoft.com/en-GB/library/ms229672(v=vs.90).aspx创建的扩展。

它可以将位图中的所有像素从一种颜色转换为另一种颜色。

 public static class BitmapExt { public static void ChangeColour(this Bitmap bmp, byte inColourR, byte inColourG, byte inColourB, byte outColourR, byte outColourG, byte outColourB) { // Specify a pixel format. PixelFormat pxf = PixelFormat.Format24bppRgb; // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, pxf); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. // int numBytes = bmp.Width * bmp.Height * 3; int numBytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[numBytes]; // Copy the RGB values into the array. Marshal.Copy(ptr, rgbValues, 0, numBytes); // Manipulate the bitmap for (int counter = 0; counter < rgbValues.Length; counter += 3) { if (rgbValues[counter] == inColourR && rgbValues[counter + 1] == inColourG && rgbValues[counter + 2] == inColourB) { rgbValues[counter] = outColourR; rgbValues[counter + 1] = outColourG; rgbValues[counter + 2] = outColourB; } } // Copy the RGB values back to the bitmap Marshal.Copy(rgbValues, 0, ptr, numBytes); // Unlock the bits. bmp.UnlockBits(bmpData); } } 

bmp.ChangeColour(0,128,0,0,0,0);调用bmp.ChangeColour(0,128,0,0,0,0);

您需要一个库,它提供了一种修改图像颜色空间的方法,而无需使用像素。 LeadTools有一个非常广泛的图像库,您可以使用它支持颜色空间修改, 包括交换颜色 。

您可以使用SetPixel :

 private void ChangeColor(Bitmap s, System.Drawing.Color source, System.Drawing.Color target) { for (int x = 0; x < s.Width; x++) { for (int y = 0; y < s.Height; y++) { if (s.GetPixel(x, y) == source) s.SetPixel(x, y, target); } } } 

GetPixel和SetPixel是gdiplus.dll函数GdipBitmapGetPixel和GdipBitmapSetPixel相应的包装器

备注 :

根据位图的格式,GdipBitmapGetPixel可能不会返回与GdipBitmapSetPixel设置的值相同的值。 例如,如果在像素格式为32bppPARGB的Bitmap对象上调用GdipBitmapSetPixel,则会对像素的RGB分量进行预乘。 由于四舍五入,后续调用GdipBitmapGetPixel可能会返回不同的值。 此外,如果在颜色深度为每像素16位的Bitmap对象上调用GdipBitmapSetPixel,则在转换过程中信息可能会丢失32到16位,随后对GdipBitmapGetPixel的调用可能会返回不同的值。