.net GZipStream 压缩与解压

ygp8 8年前

 简介:


GzipStream表示GZip 数据格式,它使用无损压缩和解压缩文件的行业标准算法。 这种格式包括一个检测数据损坏的循环冗余校验值。 GZip 数据格式使用的算法与 DeflateStream 类的算法相同,但它可以扩展以使用其他压缩格式。 这种格式可以通过不涉及专利使用权的方式轻松实现。


   实际使用中因为涉及到网络传输大量数据,直接传送简直不能忍,用GzipStream压缩了一下后再传输流量立即下降了80%,,主要是因为ASCII文本格式有比较高的压缩率所以会比较高。

   GzipStream 位于 System.IO.Compression 中

   压缩代码


public byte[] Compress(byte[] io)          {              System.IO.MemoryStream basestream = new System.IO.MemoryStream();              using (System.IO.Compression.GZipStream compressstream = new GZipStream(basestream, CompressionMode.Compress, true))              {                  compressstream.Write(io, 0, io.Length);                  compressstream.Flush();                  compressstream.Close();              }              basestream.Position = 0;              return basestream.GetBuffer();          }



解压代码



public System.IO.StringReader DeCompress(byte[] str)          {              System.IO.MemoryStream stream = new System.IO.MemoryStream();              stream.Write(str,0,str.Length);              stream.Position = 0;              GZipStream zip = new GZipStream(stream, CompressionMode.Decompress);              System.IO.StreamReader rd = new System.IO.StreamReader(zip);              return new System.IO.StringReader(rd.ReadToEnd());          }



 事实上,只有当你压缩大量字节的时候才会有明显的压缩率,如果你压少量的字节反而压缩后会更大。 一般来讲100+个字节以上才会有好的效果,小于这个值不需要压缩了。


  我实际用的过程中 压缩前为3M 压缩后 50K ,效果非常明显。

来自:http://my.oschina.net/000quanwei/blog/500729