将图像转换为位图后,背景变成黑色。

12

我需要将一张图片转换为位图。

最初,一个gif作为字节读入,然后被转换成了一张图片。

但是当我尝试将图片转换为位图时,显示在picturebox中的图像背景变为黑色,而之前是白色的。

这是代码:

    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个回答

24

不要保存为位图文件。该文件格式不支持透明度,因此图像将被保存为没有透明度的图像。

您可以使用PNG文件格式代替。这将保留透明度。

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


我也用这个方法成功了。这里有一些代码展示了这个解决方案:https://dev59.com/o2w15IYBdhLWcg3wmM19 - TripleAntigen
1
但是BMP支持透明度,不是吗? - Robula

0

System.Drawing.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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接