Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

c# - Converting Image to bitmap turns background black

I need to convert an Image to a bitmap.

initially a gif was read in as bytes and then converted to an Image.

But when I try convert the image to a bit map, the graphic displaying in my picturebox has a black background when it used to be white.

Here is the code:

    var image = (System.Drawing.Image)value;
        // Winforms Image we want to get the WPF Image from...
        var bitmap = new System.Windows.Media.Imaging.BitmapImage();
        bitmap.BeginInit();
        MemoryStream memoryStream = new MemoryStream();
        // Save to a memory stream...
        image.Save(memoryStream, ImageFormat.Bmp);
        // Rewind the stream...
        memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
        bitmap.StreamSource = memoryStream;
        bitmap.EndInit();
        return bitmap;

Can some one explain why the background is going black and how i can stop it doing this.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't save as a bitmap file. The file format doesn't support transparency, so the image will be saved without transparency.

You can use the PNG file format instead. That will preserve the transparency.

If you really need it to use the bitmap file format, you have to make it non-transparent first. Create a new bitmap with the same size, use the Graphics.FromImage method to get a graphics object to draw on the image, use the Clear method to fill it with the background color that you want, use the DrawImage method to draw your image on top of the background, and then save that bitmap.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...