GDI+: Set all pixels to given color while retaining existing alpha value

前端 未结 3 1781
萌比男神i
萌比男神i 2021-01-05 12:15

What is the best way to set the RGB components of every pixel in a System.Drawing.Bitmap to a single, solid color? If possible, I\'d like to avoid manually loop

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 12:57

    I know this is already answered, but based on Hans Passant's answer the resulting code looks something like this:

    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;
        }
    }
    

    Download a working demo here: http://benpowell.org/change-the-color-of-a-transparent-png-image-icon-on-the-fly-using-asp-net-mvc/

提交回复
热议问题