using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Common.IO.Compression
{
public class GZipCompression
{
///
/// 压缩字节流
///
/// 原字节流
/// 返回压缩后的字节流
public static byte[] Compress(byte[] baseStream)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress))
{
gs.Write(baseStream, 0, baseStream.Length);
gs.Flush();
}
byte[] rs = ms.ToArray();
ms.Close();
return rs;
}
///
/// 解压缩字节流
///
/// 经过压缩的字节流
/// 返回解压缩之后的字节流
public static byte[] Decompress(byte[] compressedStream)
{
byte[] buff = new byte[1024];
using (System.IO.MemoryStream comp = new System.IO.MemoryStream(compressedStream))
using (System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(comp, System.IO.Compression.CompressionMode.Decompress))
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
int rs = 0;
rs = gs.Read(buff, 0, buff.Length);
while (rs > 0)
{
ms.Write(buff, 0, rs);
rs = gs.Read(buff, 0, buff.Length);
}
buff = ms.ToArray();
}
return buff;
}
///
/// 压缩字节流
///
/// 原字节流
/// 返回压缩后的字节流
public static System.IO.MemoryStream Compress(System.IO.MemoryStream baseStream)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress))
{
gs.Write(baseStream.ToArray(), 0, (int)baseStream.Length);
gs.Flush();
}
return ms;
}
///
/// 解压缩字节流
///
/// 经过压缩的字节流
/// 返回解压缩之后的字节流
public static System.IO.MemoryStream Decompress(System.IO.MemoryStream compressedStream)
{
byte[] buff = new byte[1024];
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(compressedStream, System.IO.Compression.CompressionMode.Decompress))
{
int rs = 0;
rs = gs.Read(buff, 0, buff.Length);
while (rs > 0)
{
ms.Write(buff, 0, rs);
rs = gs.Read(buff, 0, buff.Length);
}
}
return ms;
}
}
}