C#用Zlib压缩或解压缩字节数组

///
/// 复制流
///
/// 原始流
/// 目标流
public static void CopyStream(System.IO.Stream input, System.IO.Stream output)
{
byte[] buffer = new byte[2000];
int len;
while ((len = input.Read(buffer, 0, 2000)) > 0)
{
output.Write(buffer, 0, len);
}
output.Flush();
}
///
/// 压缩字节数组
///
/// 需要被压缩的字节数组
/// 压缩后的字节数组
private static byte[] compressBytes(byte[] sourceByte)
{
MemoryStream inputStream = new MemoryStream(sourceByte);
Stream outStream = compressStream(inputStream);
byte[] outPutByteArray = new byte[outStream.Length];
outStream.Position = 0;
outStream.Read(outPutByteArray, 0, outPutByteArray.Length);
outStream.Close();
inputStream.Close();
return outPutByteArray;
}
///
/// 解压缩字节数组
///
/// 需要被解压缩的字节数组
/// 解压后的字节数组
private static byte[] deCompressBytes(byte[] sourceByte)
{
MemoryStream inputStream = new MemoryStream(sourceByte);
Stream outputStream = deCompressStream(inputStream);
byte[] outputBytes = new byte[outputStream.Length];
outputStream.Position = 0;
outputStream.Read(outputBytes, 0, outputBytes.Length);
outputStream.Close();
inputStream.Close();
return outputBytes;
}
///
/// 压缩流
///
/// 需要被压缩的流
/// 压缩后的流
private static Stream compressStream(Stream sourceStream)
{
MemoryStream streamOut = new MemoryStream();
ZOutputStream streamZOut = new ZOutputStream(streamOut, zlibConst.Z_DEFAULT_COMPRESSION);
CopyStream(sourceStream, streamZOut);
streamZOut.finish();
return streamOut;
}
///
/// 解压缩流
///
/// 需要被解压缩的流
/// 解压后的流
private static Stream deCompressStream(Stream sourceStream)
{
MemoryStream outStream = new MemoryStream();
ZOutputStream outZStream = new ZOutputStream(outStream);
CopyStream(sourceStream, outZStream);
outZStream.finish();
return outStream;
}

zlib.NET库下载:http://www.componentace.com/zlib_.NET.htm

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值