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

Cha*_*les 7 c# gdi+ bitmap

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

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

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

Han*_*ant 14

是的,使用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
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢汉斯.我错过了分裂255,这让我疯了!如果有兴趣的话,我已经整理了一个可下载的演练和示例:http://blog.benpowell.co.uk/2011/01/change-color-of-transparent-png-image.html (2认同)

Reb*_*cca 7

我知道这已经回答了,但根据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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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