2014-02-05 66 views
0

如何直接從zipfile加載圖像源。Wpf:從zip中加載圖像源而不保存文件

我使用DotNetZip。

2個以下代碼示例。

代碼示例1未能加載並顯示圖像文件。

代碼示例1 我將一個zipEntry加載到MemoryStream,並創建一個BitmapImage用作Imagesource,但它失敗。 只是爲了測試,我嘗試從內存流中保存圖像,以確保Zip條目已加載。它被正確保存:

 MemoryStream memoryStream1 = new MemoryStream(); 

     ZipFile zip = ZipFile.Read(@"D:\myZipArcive.zip"); 

     ZipEntry myEntry = zip["myfile.jpg"]; 
     myEntry.Extract(memoryStream1); 
     memoryStream1.Close(); 

     System.IO.File.WriteAllBytes(@"D:\saved.jpg", memoryStream1.ToArray()); 
     //save file just for testing 

     BitmapImage src = new BitmapImage(); 
     src.BeginInit(); 
     src.CacheOption = BitmapCacheOption.OnLoad; 
     src.StreamSource = memoryStream1; 
     src.EndInit(); 

     myImage.Source = src as ImageSource; //no image is displayed 

代碼示例2 予加載文件到一個MemoryStream,並創建一個BitmapImage的將被用作具有的ImageSource更迭。

 FileStream fileStream = File.OpenRead(@"D:\myFile.jpg"); 

     MemoryStream memoryStream2 = new MemoryStream(); 
     memoryStream2.SetLength(fileStream.Length); 
     fileStream.Read(memoryStream2.GetBuffer(), 0, (int)fileStream.Length); 

     BitmapImage src = new BitmapImage(); 
     src.BeginInit(); 
     src.CacheOption = BitmapCacheOption.OnLoad; 
     src.StreamSource = memoryStream2;  
     src.EndInit(); 

     myImage.Source = src as ImageSource; //The image is displayed 

什麼是錯的樣品將MemoryStream 1 我得到一個調試消息,當我執行樣品1: 「‘System.NotSupportedException’類型的第一次機會異常出現在mscorlib.dll」

回答

1

流似乎被Extract方法關閉。

var zipFile = ZipFile.Read(@"D:\myZipArcive.zip"); 
var zipEntry = zipFile["myfile.jpg"]; 
var zipStream = new MemoryStream(); 
zipEntry.Extract(zipStream); 

var bitmap = new BitmapImage(); 

using (var sourceStream = new MemoryStream(zipStream.ToArray())) 
{ 
    bitmap.BeginInit(); 
    bitmap.CacheOption = BitmapCacheOption.OnLoad; 
    bitmap.StreamSource = sourceStream; 
    bitmap.EndInit(); 
} 

myImage.Source = bitmap; 

更新:您可以然而從第一個緩衝區創建第二個的MemoryStream因爲你事先知道圖像緩衝區的未壓縮的大小,你可能略有通過手動設置緩衝提高性能這兩個MemoryStreams操作上:

var buffer = new byte[zipEntry.UncompressedSize]; 
var zipStream = new MemoryStream(buffer); // here 
zipEntry.Extract(zipStream); 
... 
using (var sourceStream = new MemoryStream(buffer)) // and here 
... 
+0

嘿克萊門斯感謝。它很棒! –

+0

@ErikT請參閱我的更新。也許這會表現得更好一些。 – Clemens

0

這工作太:

var zipFile = ZipFile.Read(@"D:\myZipArcive.zip"); 
var zipEntry = zipFile["myfile.jpg"]; 
var bitmap = new BitmapImage(); 
bitmap.BeginInit(); 
bitmap.CacheOption = BitmapCacheOption.OnLoad; 
bitmap.StreamSource = zipEntry.OpenReader(); 
bitmap.EndInit(); 
myImage.Source = bitmap; 
+0

經過一些測試後,我注意到,使用Clement的代碼加載圖片的速度要快得多。 –

相關問題