GDI +:将所有像素设置为给定颜色,同时保留现有的alpha值

System.Drawing.Bitmap中每个像素的RGB分量设置为单一纯色的最佳方法是什么? 如果可能的话,我想避免手动循环每个像素来执行此操作。

注意:我想保留原始位图中的相同alpha分量。 我只想改变RGB值。

我研究了使用ColorMatrixColorMap ,但我找不到任何方法可以使用任何一种方法将所有像素设置为特定的给定颜色。

是的,使用ColorMatrix。 应该看起来像这样:

  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 RGB 0 1 

其中R,G和B是替换颜色的缩放颜色值(除以255.0f)

我知道这已经回答了,但根据Hans Passant的回答,生成的代码看起来像这样:

 public class Recolor { public static Bitmap Tint(string filePath, Color c) { // load from file Image original = Image.FromFile(filePath); original = new Bitmap(original); //get a graphics object from the new image Graphics g = Graphics.FromImage(original); //create the ColorMatrix ColorMatrix colorMatrix = new ColorMatrix( new float[][]{ new float[] {0, 0, 0, 0, 0}, new float[] {0, 0, 0, 0, 0}, new float[] {0, 0, 0, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {cR / 255.0f, cG / 255.0f, cB / 255.0f, 0, 1} }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the color matrix g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); //dispose the Graphics object g.Dispose(); //return a bitmap return (Bitmap)original; } } 

在这里下载一个工作演示: http : //benpowell.org/change-the-color-of-a-transparent-png-image-icon-on-the-fly-using-asp-net-mvc/

最好(至少在perf方面)选项是使用Bitmap.LockBits ,并循环扫描线中的像素数据,设置RGB值。

由于您不想更改Alpha,因此您将不得不遍历每个像素 – 没有单个内存分配将保留alpha并替换RGB,因为它们是交错在一起的。