【发布时间】:2011-01-31 09:17:54
【问题描述】:
将System.Drawing.Bitmap 中每个像素的 RGB 分量设置为单一纯色的最佳方法是什么?如果可能的话,我想避免手动循环遍历每个像素来执行此操作。
注意:我想保留与原始位图相同的 alpha 分量。我只想更改 RGB 值。
我研究过使用ColorMatrix 或ColorMap,但我找不到任何方法将所有像素设置为特定的给定颜色。
【问题讨论】:
将System.Drawing.Bitmap 中每个像素的 RGB 分量设置为单一纯色的最佳方法是什么?如果可能的话,我想避免手动循环遍历每个像素来执行此操作。
注意:我想保留与原始位图相同的 alpha 分量。我只想更改 RGB 值。
我研究过使用ColorMatrix 或ColorMap,但我找不到任何方法将所有像素设置为特定的给定颜色。
【问题讨论】:
最好的(至少就性能而言)选项是使用Bitmap.LockBits,并循环遍历扫描线中的像素数据,设置 RGB 值。
由于您不想更改 Alpha,因此您将不得不遍历每个像素 - 没有单一的内存分配可以保留 Alpha 并替换 RGB,因为它们是交错在一起的。
【讨论】:
是的,使用 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)
【讨论】:
我知道这已经得到解答,但根据 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[] {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/
【讨论】: