字符压缩,压缩的整体说:https://blog.csdn.net/lanmenghcc/article/details/40071923
总计:
1.7z压缩率最高,没测试,但只能文件压缩不能字符串压缩。
2.GZip和zlib可以进行字符串流压缩,对比GZip一般为文件压缩,压缩数据还是用的zlib。zlib为纯数据的压缩,压缩完比gzip少16个字节的头部文件标识。
3.gzip微软系统包有集成、zlib需要另外引入包。
4.压缩测试对于字符串比较小,大概256字符串左右,压缩字符串比压缩前还大。毕竟压缩还是要标记些东西
对比下来还是用gzip压缩。
下面贴代码GZip压缩和解压:
压缩
/// <summary> /// GZip压缩 256字节以上才有压缩效果 /// </summary> /// <param name="strData">压缩字符串</param> /// <returns></returns> public static string Compress(string strData) { try { byte[] data = Encoding.GetEncoding("UTF-8").GetBytes(strData); using (var ms = new MemoryStream()) { using (var zip = new GZipStream(ms, CompressionMode.Compress, true)) { zip.Write(data, 0, data.Length); } var buffer = new byte[ms.Length]; ms.Position = 0; ms.Read(buffer, 0, buffer.Length); return Convert.ToBase64String(buffer); } } catch (Exception ex) { return null; } }
解压:
try { byte[] data = Convert.FromBase64String(strData); using (var ms = new MemoryStream(data)) { using (var zip = new GZipStream(ms, CompressionMode.Decompress, true)) { using (var msreader = new MemoryStream()) { var buffer = new byte[0x1000];//4M存储大小 while (true) { var reader = zip.Read(buffer, 0, buffer.Length); if (reader <= 0) { break; } msreader.Write(buffer, 0, reader); } msreader.Position = 0; buffer = msreader.ToArray(); return Encoding.GetEncoding("UTF-8").GetString(buffer); } } } } catch (Exception ex) { return null; }
zlib压缩和解压:
压缩:
public static string Zip(string value) { byte[] byteArray = Encoding.UTF8.GetBytes(value); byte[] tmpArray; using (MemoryStream ms = new MemoryStream()) { using (zlib.ZOutputStream outZStream = new zlib.ZOutputStream(ms, zlib.zlibConst.Z_DEFAULT_COMPRESSION)) { outZStream.Write(byteArray, 0, byteArray.Length); outZStream.Flush(); } tmpArray = ms.ToArray(); } return Convert.ToBase64String(tmpArray); }
解压:有点长没缩减
/// <summary> /// 解压缩字节数组 /// </summary> /// <param name="sourceByte">需要被解压缩的字节数组</param> /// <returns>解压后的字节数组</returns> 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; } /// <summary> /// 解压缩流 /// </summary> /// <param name="sourceStream">需要被解压缩的流</param> /// <returns>解压后的流</returns> private static Stream deCompressStream(Stream sourceStream) { MemoryStream outStream = new MemoryStream(); ZOutputStream outZStream = new ZOutputStream(outStream); CopyStream(sourceStream, outZStream); outZStream.finish(); return outStream; } /// <summary> /// 复制流 /// </summary> /// <param name="input">原始流</param> /// <param name="output">目标流</param> 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(); }