从PNG到BitmapImage。 透明度问题。

我有一些问题。 我试图在我的viewModel中将png-image从资源加载到BitmapImage propery,如下所示:

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图像? 谢谢,帕维尔。

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; } } 

这是因为BMP文件格式不支持PNG文件格式的透明度。 如果你想要透明度,你将不得不使用PNG

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

这通常是由64位深度PNG图像引起的, BitmapImage不支持这种图像。 Photoshop似乎错误地将这些显示为16位,因此您需要使用Windows资源管理器进行检查:

  • 右键单击该文件。
  • 单击属性。
  • 转到详细信息选项卡。
  • 寻找“比特深度” – 它通常在图像部分,具有宽度和高度。

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

我查看了这篇文章,找到了与此相同的透明度问题的答案。

但后来我看到了给出的示例代码,只是想分享这段代码来从Resources加载Image。

 Image connection = Resources.connection; 

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