2012-07-18 220 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; 
    } 
}