2017-04-21 23 views
-1

我有一個圖像的字節數組,我想從它創建Zip文件。如何Zip一個圖像的MemoryStream

我可以成功保存jpg文件中的字節數組,但是當我從它創建zip文件時,zip文件(進入zip文件的圖像)的圖像已損壞,我無法打開它! (當我嘗試打開圖像,用Winrar顯示錯誤消息波紋管: d:\ sample.zip:歸檔是無論是在未知的格式或損壞 )

注:我的形象是在內存中,我不不想創建物理圖像文件。

這裏是我的代碼:

private void Zip(byte[] imageBytes) 
{ 
    string filePath = string.Empty; 
    using (var ms = new MemoryStream()) 
    using (var zip = new ZipArchive(ms, ZipArchiveMode.Create)) 
    { 
     var entry = zip.CreateEntry("sample.jpg", CompressionLevel.Optimal); 

     using (var entryStream = entry.Open()) 
     using (var fileToCompressStream = new MemoryStream(imageBytes)) 
     { 
      fileToCompressStream.CopyTo(entryStream); 
     } 

     using (var fs = new FileStream(baseFilePath + "sample.zip", FileMode.Create)) 
     { 
      ms.Position = 0; 
      ms.WriteTo(fs); 
     } 
    } 
} 
+0

我還創建imageBytes(參數)的新位圖實例,並將其保存到entryStream,但同樣的問題! – Moradof

回答

0

你應該能夠只是做:

using System.IO; 
using System.IO.Compression; 
using System.Text; 

private void Zip (byte[] imageBytes) { 

string fileName = baseFilePath + "sample.zip"; 
using (FileStream f2 = new FileStream(fileName, FileMode.Create)){ 
     using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false)) 
     { 
      gz.Write(imageBytes, 0, imageBytes.Length); 
     } 
    } 
} 
+0

它工作正常。謝謝。我怎樣才能設置圖像文件的名稱? (它保存與沒有任何擴展名的zip文件相同的名稱) – Moradof

+0

我認爲,GZip不適合我的情況,因爲我最終需要將多個圖像放在一個zip文件中,據我所知,GZipStream適用於zip文件。我對嗎 ? – Moradof

+0

你是正確的閱讀這裏如何做多個文件:http://stackoverflow.com/questions/24571773/how-do-i-zip-multiple-files-using-gzipstream-in-c-sharp – Avitus

相關問題