VB进行GZIP解压的,DLL是系统的,如果没有 [点击下载]
Option Explicit
'GZIP API
'--------------------------------------------------
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Declare Function InitDecompression Lib "gzip.dll" () As Long
Private Declare Function CreateDecompression Lib "gzip.dll" (ByRef context As Long, ByVal Flags As Long) As Long
Private Declare Function DestroyDecompression Lib "gzip.dll" (ByRef context As Long) As Long
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
'=============================================================
'2012-10-5
'gzip解压,返回值表示是否成功,如果成功,解压结果通过址参回传
'=============================================================
Public Function UnGzip(ByRef arrBit() As Byte) As Boolean
On Error GoTo errline
Dim SourceSize As Long
Dim buffer() As Byte
Dim lReturn As Long
Dim outUsed As Long
Dim inUsed As Long
Dim chandle As Long
If arrBit() <> &H1F Or arrBit() <> &H8B Or arrBit() <> &H8 Then
Exit Function '不是GZIP数据的字节流
End If
'获取原始长度
'GZIP格式的最后4个字节表示的是原始长度
'与最后4个字节相邻的4字节是CRC32位校验,用于比对是否和原数据匹配
lReturn = UBound(arrBit) -
CopyMemory SourceSize, arrBit(lReturn),
'重点在这里,网上有些代码计算解压存放空间用了一些奇怪的公式
'如:L = 压缩大小 * (1 + 0.01) + 12
'不知道怎么得到的,用这种方式偶尔会报错...
'这里的判断是因为:(维基)一个压缩数据集包含一系列的block(块),只要未压缩数据大小不超过65535字节,块的大小是任意的。
'GZIP基本头是10字节
If SourceSize > Or SourceSize < Then
'测试用,申请100KB空间尝试一下
'SourceSize = 102400
Exit Function
Else
SourceSize = SourceSize +
End If
ReDim buffer(SourceSize) As Byte
'创建解压缩进程
InitDecompression
CreateDecompression chandle, '创建
'解压缩数据
Decompress ByVal chandle, arrBit(), UBound(arrBit) + , buffer(), SourceSize + , inUsed, outUsed
If outUsed <> Then
DestroyDecompression chandle
ReDim arrBit(outUsed - )
CopyMemory arrBit(), buffer(), outUsed
UnGzip = True
End If
Exit Function
errline:
End Function
C#进行GZIP压缩和解压,参考[MSDN]
public static byte[] GZipCompress(byte[] buffer)
{
using (MemoryStream ms = new MemoryStream())
{
GZipStream Compress = new GZipStream(ms, CompressionMode.Compress);
Compress.Write(buffer, , buffer.Length);
Compress.Close();
return ms.ToArray();
}
}
public static byte[] GZipDecompress(byte[] buffer)
{
using (MemoryStream tempMs = new MemoryStream())
{
using (MemoryStream ms = new MemoryStream(buffer))
{
GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress);
Decompress.CopyTo(tempMs);
Decompress.Close();
return tempMs.ToArray();
}
}
}