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

时间:2010-11-01 08:23:00

标签: 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;

有人可以解释为什么背景变黑以及我如何阻止背景。

由于

2 个答案:

答案 0 :(得分:21)

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

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

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

答案 1 :(得分:0)

System.Drawing.Bitmap 和 Bitmap 文件格式之间存在差异。您可以使用透明层保存 System.Drawing.Bitmap,因为它完全支持它。

var image = (System.Drawing.Image)value;
Bitmap bitmap = new Bitmap(image); //Make a Bitmap from the image
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Png); //Format it as PNG so the transparency layer remains.
//Rest of the code...

bmp 文件格式还可以通过特定方式支持透明度。阅读this