【问题标题】:Converting Image to bitmap turns background black将图像转换为位图会使背景变黑
【发布时间】:2011-05-03 07:39:53
【问题描述】:

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

最初以字节形式读取 gif,然后将其转换为图像。

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

代码如下:

    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;

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

谢谢

【问题讨论】:

    标签: c# image bitmap


    【解决方案1】:

    不要保存为位图文件。文件格式不支持透明,所以图片会不透明保存。

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

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

    【讨论】:

    【解决方案2】:

    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

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多