从PNG到BitmapImage。透明度问题。

3

我有一个问题。我正在尝试从资源中加载png图像到我的viewModel的BitmapImage属性中,代码如下:

Bitmap bmp = Resource1.ResourceManager.GetObject(String.Format("_{0}",i)) as Bitmap;
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Bmp);
BitmapImage bImg = new BitmapImage();

bImg.BeginInit();
bImg.StreamSource = new MemoryStream(ms.ToArray());
bImg.EndInit();

this.Image = bImg;

但是当我这样做时,图片的透明度会丢失。所以问题是如何从资源中加载png图像而不丢失透明度呢?谢谢,Pavel。


1
@Felice Pollano:你应该恢复你删除的答案,那个答案很好。将图像保存为 .bmp 文件并加载它显然会丢失透明度。 - Julien Lebosquain
4个回答

8

Ria的回答帮助我解决了透明度问题。这是对我有用的代码:

public BitmapImage ToBitmapImage(Bitmap bitmap)
{
  using (MemoryStream stream = new MemoryStream())
  {
    bitmap.Save(stream, ImageFormat.Png); // Was .Bmp, but this did not show a transparent background.

    stream.Position = 0;
    BitmapImage result = new BitmapImage();
    result.BeginInit();
    // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
    // Force the bitmap to load right now so we can dispose the stream.
    result.CacheOption = BitmapCacheOption.OnLoad;
    result.StreamSource = stream;
    result.EndInit();
    result.Freeze();
    return result;
  }
}

4

这是因为文件格式不支持透明度,而文件格式支持透明度。如果您想要透明度,您需要使用格式。

尝试使用ImageFormat.Png进行保存。


0

这通常是由于64位深度的PNG图像引起的,而BitmapImage不支持。Photoshop似乎错误地将其显示为16位,所以您需要通过Windows资源管理器进行检查:

  • 右键单击文件。
  • 点击属性。
  • 转到详细信息选项卡。
  • 查找“位深度” - 它通常在图像部分,与宽度和高度一起。

如果显示为64,您需要使用16位深度重新编码图像。我建议使用Paint.NET,因为它可以正确处理PNG位深度。


0

我看了这篇帖子,想找到解决透明度问题的答案,就像这里一样。

但是后来我看到了给出的示例代码,只是想分享一下从资源中加载图像的代码。

Image connection = Resources.connection;

使用这个工具,我发现我不需要将我的图像重新编码为16位。谢谢。

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