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

前端 未结 3 1739
萌比男神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条回答
  • 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/

    0 讨论(0)
  • 2021-01-05 12:57

    The best (in terms of perf, at least) option is to use Bitmap.LockBits, and loop through the pixel data in the scan line, setting the RGB values.

    Since you don't want to change the Alpha, you are going to have to loop through each pixel - there is no single memory assignment that will preserve alpha and replace RGB, since they're interleaved together.

    0 讨论(0)
  • 2021-01-05 13:01

    Yes, use a ColorMatrix. It ought to look like this:

      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
    

    Where R, G and B are the scaled color values of the replacement color (divide by 255.0f)

    0 讨论(0)
提交回复
热议问题