从巴纽的BitmapImage。透明度问题。透明度、问题、BitmapImage

2023-09-03 22:05:11 作者:愉快遗忘

我有一些问题。 我试图加载从资源PNG图像,以BitmapImage的属性格式在我的视图模型是这样的:

I've got some issue. I'm trying to load png-image from resources to BitmapImage propery in my viewModel like this:

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图像不透明度的损失? 谢谢, 帕维尔。

But when I do it, I lose the transparency of the image. So the question is how can I load png image from resources without loss of transparency? Thanks, Pavel.

推荐答案

利雅的回答帮我解决透明度问题。这里的code,它为我的作品:

Ria's answer helped me resolve the transparency problem. Here's the code that works for me:

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