2012-07-18 213 views
2

我有一些问题。 我试图加载从资源的PNG图像的BitmapImage属性格式在我的视图模型是这样的:从PNG到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

@feelice pollano:你应该恢复你删除的答案,这是很好的。将图像保存为.bmp文件并加载它将明显失去透明度。 – 2012-07-18 08:06:32

回答

0

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

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

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

2

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

尝试ImageFormat.Png进行保存。

0

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

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

Image connection = Resources.connection; 

使用此我发现我不需要重新编码我的图像到16位。谢谢。

3

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