c# - 从 PNG 到 BitmapImage。透明度问题。

标签 c# .net wpf

我有一些问题。 我正在尝试将资源中的 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 图像? 谢谢, 帕维尔。

最佳答案

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

关于c# - 从 PNG 到 BitmapImage。透明度问题。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11536577/

相关文章:

javascript - 将动态json添加到静态json

c# - 在MVVM中,当一个属性的值依赖于另一个属性时,是否有一种标准方法可以自动NotifyPropertyChanged?

c# - 使用数组的 SetValue 方法与 [] 索引器

c# - 如何从 Win32 进程调用 .NET DLL?

.NET 4.0 - Microsoft.Windows.Shell - 它在哪里?

c# - 在 C# 中按共享属性对不同对象的列表进行排序

asp.net - 将 WCF 库项目转换为 WCF Web 服务(WCF 应用程序)项目类型

c# - 从代码中关闭 Material Design DialogHost

wpf - 将 WPF ListView 滚动到特定行

c# - 在 rdlc 中调用钻取报告