VB進行GZIP解壓的,DLL是系統的,若是沒有 [點擊下載]測試
1 Option Explicit 2 'GZIP API 3 '-------------------------------------------------- 4 Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long) 5 Private Declare Function InitDecompression Lib "gzip.dll" () As Long 6 Private Declare Function CreateDecompression Lib "gzip.dll" (ByRef context As Long, ByVal Flags As Long) As Long 7 Private Declare Function DestroyDecompression Lib "gzip.dll" (ByRef context As Long) As Long 8 Private Declare Function Decompress Lib "gzip.dll" (ByVal context As Long, inBytes As Any, ByVal input_size As Long, outBytes As Any, ByVal output_size As Long, ByRef input_used As Long, ByRef output_used As Long) As Long 9 '============================================================= 10 '2012-10-5 11 'gzip解壓,返回值表示是否成功,若是成功,解壓結果經過址參回傳 12 '============================================================= 13 Public Function UnGzip(ByRef arrBit() As Byte) As Boolean 14 On Error GoTo errline 15 Dim SourceSize As Long 16 Dim buffer() As Byte 17 Dim lReturn As Long 18 Dim outUsed As Long 19 Dim inUsed As Long 20 Dim chandle As Long 21 If arrBit(0) <> &H1F Or arrBit(1) <> &H8B Or arrBit(2) <> &H8 Then 22 Exit Function '不是GZIP數據的字節流 23 End If 24 '獲取原始長度 25 'GZIP格式的最後4個字節表示的是原始長度 26 '與最後4個字節相鄰的4字節是CRC32位校驗,用於比對是否和原數據匹配 27 lReturn = UBound(arrBit) - 3 28 CopyMemory SourceSize, arrBit(lReturn), 4 29 '重點在這裏,網上有些代碼計算解壓存放空間用了一些奇怪的公式 30 '如:L = 壓縮大小 * (1 + 0.01) + 12 31 '不知道怎麼獲得的,用這種方式偶爾會報錯... 32 '這裏的判斷是由於:(維基)一個壓縮數據集包含一系列的block(塊),只要未壓縮數據大小不超過65535字節,塊的大小是任意的。 33 'GZIP基本頭是10字節 34 If SourceSize > 65535 Or SourceSize < 10 Then 35 '測試用,申請100KB空間嘗試一下 36 'SourceSize = 102400 37 Exit Function 38 Else 39 SourceSize = SourceSize + 1 40 End If 41 ReDim buffer(SourceSize) As Byte 42 '建立解壓縮進程 43 InitDecompression 44 CreateDecompression chandle, 1 '建立 45 '解壓縮數據 46 Decompress ByVal chandle, arrBit(0), UBound(arrBit) + 1, buffer(0), SourceSize + 1, inUsed, outUsed 47 If outUsed <> 0 Then 48 DestroyDecompression chandle 49 ReDim arrBit(outUsed - 1) 50 CopyMemory arrBit(0), buffer(0), outUsed 51 UnGzip = True 52 End If 53 Exit Function 54 errline: 55 End Function
C#進行GZIP壓縮和解壓,參考[MSDN]spa
1 public static byte[] GZipCompress(byte[] buffer) 2 { 3 using (MemoryStream ms = new MemoryStream()) 4 { 5 GZipStream Compress = new GZipStream(ms, CompressionMode.Compress); 6 Compress.Write(buffer, 0, buffer.Length); 7 Compress.Close(); 8 return ms.ToArray(); 9 } 10 } 11 public static byte[] GZipDecompress(byte[] buffer) 12 { 13 using (MemoryStream tempMs = new MemoryStream()) 14 { 15 using (MemoryStream ms = new MemoryStream(buffer)) 16 { 17 GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress); 18 Decompress.CopyTo(tempMs); 19 Decompress.Close(); 20 return tempMs.ToArray(); 21 } 22 } 23 }