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]
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 }
时间: 2024-10-07 05:31:56