压缩与解压缩 ZipHelper
我在AgileIM的开发中解决视频/音频会话功能时,发现传输的音/视频数据量太大,通过一些格式转换(如BMP->JPG、或 帧间预测编码)可以适当减少带宽的需求,但是仍然不能满足需求,于是我想到了数据压缩,经过我测试、普通的音/视频数据经压缩后可以只有原来的一半大小,基本可以满足需要了。压缩/解压功能我借助了ICSharpCode.SharpZipLib 类库,为了更方便易用,我封装了ZipHelper类,实现如下:
public static class ZipHelper
{
public static byte[] Zip(byte[] data)
{
MemoryStream mstream = new MemoryStream();
BZip2OutputStream zipOutStream = new BZip2OutputStream(mstream);
zipOutStream.Write(data, 0, data.Length);
zipOutStream.Finalize();
zipOutStream.Close();
byte[] result = mstream.ToArray();
mstream.Close();
return result;
}
public static byte[] Unzip(byte[] data)
{
MemoryStream mstream = new MemoryStream(data);
BZip2InputStream zipInputStream = new BZip2InputStream(mstream);
byte[] byteUncompressed = new byte[zipInputStream.Length];
zipInputStream.Read(byteUncompressed, 0, (int)byteUncompressed.Length);
zipInputStream.Close();
mstream.Close();
return byteUncompressed;
}
}
{
public static byte[] Zip(byte[] data)
{
MemoryStream mstream = new MemoryStream();
BZip2OutputStream zipOutStream = new BZip2OutputStream(mstream);
zipOutStream.Write(data, 0, data.Length);
zipOutStream.Finalize();
zipOutStream.Close();
byte[] result = mstream.ToArray();
mstream.Close();
return result;
}
public static byte[] Unzip(byte[] data)
{
MemoryStream mstream = new MemoryStream(data);
BZip2InputStream zipInputStream = new BZip2InputStream(mstream);
byte[] byteUncompressed = new byte[zipInputStream.Length];
zipInputStream.Read(byteUncompressed, 0, (int)byteUncompressed.Length);
zipInputStream.Close();
mstream.Close();
return byteUncompressed;
}
}
ICSharpCode.SharpZipLib 类库可以从这里下载。