Reputation: 2987
I'm working on a Machine Learning problem at college and my first job is to convert images into black and white.
The problem is that my image has transparency, and I don't know how to remove it.
What I am trying:
public static Bitmap RemoveTransparency (Bitmap src)
{
Bitmap target = new Bitmap (src.Size.Width, src.Size.Height);
Graphics g = Graphics.FromImage (target);
g.Clear (Color.White);
g.DrawImage (src, 0, 0);
return target;
}
An example of an input image:
An example of output image after "RemoveTransparency" call:
Does anyone know what's going on? Seems like background an the letters have the same color... and my my background is black if I'm coloring to white?
Thank you!
Upvotes: 4
Views: 2836
Reputation: 79441
You need to set the CompositingMode
of your Graphics
object to SourceOver
before drawing the other image on top of it.
g.Clear(Color.White);
g.CompositingMode = CompositingMode.SourceOver;
g.DrawImage(src, 0, 0);
The default CompositingMode
is SourceCopy
, which is taking the transparent black (R=G=B=A=0) pixels in your src
image and rendering them as black pixels. SourceOver
will do alpha blending, which is what you're looking for.
See here for details: CompositingMode Enumeration
Upvotes: 5