Convert transparent png in color to single color
If the image doesn't use alpha channel for transparency then the following will do:
Bitmap image;
for (int x = 0; x < image.Width; x++)
{
for (int y = 0; y < image.Height; y++)
{
if (image.GetPixel(x, y) != Color.Transparent)
{
image.SetPixel(x, y, Color.White);
}
}
}
The other answers was helpful and got me going, thanks a lot. I couldn't make them work though, not sure why. But I also found out that I wanted to keep the original alpha value of the pixels, rendering the edges smooth. This is what I came up with.
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
Color bitColor = bitmap.GetPixel(x, y);
//Sets all the pixels to white but with the original alpha value
bitmap.SetPixel(x, y, Color.FromArgb(bitColor.A, 255, 255, 255));
}
}
Here is a screen dump of the result magnified a few times (original on top):
(source: codeodyssey.se)
SetPixel
is just about the slowest possible way to do that. You can use a ColorMatrix
instead:
var newImage = new Bitmap(original.Width, original.Height,
original.PixelFormat);
using (var g = Graphics.FromImage(newImage)) {
var matrix = new ColorMatrix(new[] {
new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
new float[] { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f },
new float[] { 1.0f, 1.0f, 1.0f, 0.0f, 1.0f }
});
var attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix);
g.DrawImage(original,
new Rectangle(0, 0, original.Width, original.Height),
0, 0, original.Width, original.Height,
GraphicsUnit.Pixel, attributes);
}