Can you change one colour to another in an Bitmap image?

前端 未结 4 1973
别跟我提以往
别跟我提以往 2021-01-02 12:53

For Bitmap, there is a MakeTransparent method, is there one similar for changing one color to another?

// This sets Color.White to          


        
4条回答
  •  没有蜡笔的小新
    2021-01-02 13:32

    Lifting the code from this answer:

    public static class BitmapExtensions
    {
        public static Bitmap ChangeColor(this Bitmap image, Color fromColor, Color toColor)
        {
            ImageAttributes attributes = new ImageAttributes();
            attributes.SetRemapTable(new ColorMap[]
            {
                new ColorMap()
                {
                    OldColor = fromColor,
                    NewColor = toColor,
                }
            }, ColorAdjustType.Bitmap);
    
            using (Graphics g = Graphics.FromImage(image))
            {
                g.DrawImage(
                    image,
                    new Rectangle(Point.Empty, image.Size),
                    0, 0, image.Width, image.Height,
                    GraphicsUnit.Pixel,
                    attributes);
            }
    
            return image;
        }
    }
    

    While I haven't benchmarked it, this should be faster than any solution that's doing GetPixel/SetPixel in a loop. It's also a bit more straightforward.

提交回复
热议问题