GDI+: Set all pixels to given color while retaining existing alpha value
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 looping through each pixel to do this.
Note: I want to keep the same alpha component from the original bitmap. I only want to change the RGB values.
I looked into using a ColorMatrix
or ColorMap
, but I couldn't find any way to set all pixels to a specific given co开发者_开发百科lor with either approach.
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)
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/
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.
精彩评论