将System.Drawing.Bitmap
中每个像素的RGB分量设置为单一纯色的最佳方法是什么?如果可能的话,我想避免手动循环每个像素来做到这一点。GDI +:将所有像素设置为给定颜色,同时保留现有的alpha值
注意:我想保留原始位图中相同的alpha分量。我只想改变RGB值。
我看着使用ColorMatrix
或ColorMap
,但我找不到任何方式的所有像素设定为与这两种方法具体给定的颜色。
将System.Drawing.Bitmap
中每个像素的RGB分量设置为单一纯色的最佳方法是什么?如果可能的话,我想避免手动循环每个像素来做到这一点。GDI +:将所有像素设置为给定颜色,同时保留现有的alpha值
注意:我想保留原始位图中相同的alpha分量。我只想改变RGB值。
我看着使用ColorMatrix
或ColorMap
,但我找不到任何方式的所有像素设定为与这两种方法具体给定的颜色。
是的,使用ColorMatrix。它应该是这样的:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 1 0
R G B 0 1
其中R,G和B是更换颜色的缩放的颜色值(由255.0f分)
最好的(就perf而言,至少)选项是使用Bitmap.LockBits,并循环扫描线中的像素数据,设置RGB值。
由于您不想更改Alpha,因此您将不得不遍历每个像素 - 没有单个内存分配可保留Alpha并替换RGB,因为它们交错在一起。
+1。谢谢里德,我可能会用它来做我正在做的其他事情。 – Charles 2010-03-24 21:10:46
我知道这已经回答了,但基于汉斯顺便的回答产生的代码看起来是这样的:
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[] {c.R/255.0f,
c.G/255.0f,
c.B/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/
这不会将每个像素的颜色设置为特定颜色,是吗?我敢肯定,这将增加R,G和B每个颜色通道。我希望整个图像是一个纯色,同时保留每个像素的透明度/ alpha。 – Charles 2010-03-24 19:32:48
对角线上的零点会产生黑色,底部的数字会被添加。 – 2010-03-24 19:38:13
啊哈。我没有想到这一切。我敢打赌,应该完美地工作。我会检查并马上回来。 – Charles 2010-03-24 20:55:25