Replace transparent background with white color in PNG images

I have a PNG image sent from a DrawingView in Android to a WCF service. The image is sent as 32-bit and has a transparent background. I want to replace the transparent color (due to the lack of a better word) of a background with white. So far, my code looks like this:

 // Converting image to Bitmap object Bitmap i = new Bitmap(new MemoryStream(Convert.FromBase64String(image))); // The image that is send from the tablet is 1280x692 // So we need to crop it Rectangle cropRect = new Rectangle(640, 0, 640, 692); //HERE Bitmap target = i.Clone(cropRect, i.PixelFormat); target.Save(string.Format("c:\\images\\{0}.png", randomFileName()), System.Drawing.Imaging.ImageFormat.Png); 

The above works fine, except that the images have a transparent background. I noticed that in Paint.NET you can just set the PNG format to 8 bits and set the background color to white. However, when I tried to use:

 System.Drawing.Imaging.PixelFormat.Format8bppIndexed 

everything i got was completely black.

Q: How to replace a transparent background with white in png?

PS. Image is in grayscale.

+5
source share
1 answer

This will be drawn on the given color:

 Bitmap Transparent2Color(Bitmap bmp1, Color target) { Bitmap bmp2 = new Bitmap(bmp1.Width, bmp1.Height); Rectangle rect = new Rectangle(Point.Empty, bmp1.Size); using (Graphics G = Graphics.FromImage(bmp2) ) { G.Clear(target); G.DrawImageUnscaledAndClipped(bmp1, rect); } return bmp2; } 

This uses the value G.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; which is the default value. It mixes the framed image with the background according to the alpha channel of the drawn image.

+12
source

Source: https://habr.com/ru/post/1208439/


All Articles