将图像转换为位图会将背景变为黑色

我需要将图像转换为位图。

最初,gif以字节forms读入,然后转换为Image。

但是,当我尝试将图像转换为位图时,我的图片框中显示的图形在以前是白色时具有黑色背景。

这是代码:

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; 

有人可以解释为什么背景会变黑并且我怎么能阻止它这样做。

谢谢

不要保存为位图文件。 文件格式不支持透明度,因此图像将保存而不透明。

您可以改用PNG文件格式。 这将保持透明度。

如果你真的需要它来使用位图文件格式,你必须先使它不透明。 创建一个大小相同的新位图,使用Graphics.FromImage方法获取要在图像上绘制的图形对象,使用Clear方法用您想要的背景颜色填充它,使用DrawImage方法绘制图像顶部的背景,然后保存该位图。