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

Set*_*ker 9 c# image bitmap

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

最初,gif以字节形式读入,然后转换为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;
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么背景会变黑以及我如何阻止它这样做.

谢谢

Guf*_*ffa 21

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

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

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