GZip压缩

作者:追风剑情 发布于:2020-9-1 12:03 分类:C#

using System;
using System.Text;
using System.IO.Compression;
using System.IO;

/// <summary>
/// GZip算法比较适合压缩大量文本数据
/// 不适合压缩图片(压缩后反而会变大)
/// </summary>
public static class GZipUtil
{
	public static string Compress(string input)
	{
		if (string.IsNullOrEmpty(input))
			return input;
		byte[] buffer = Encoding.UTF8.GetBytes(input);
		byte[] compressBuffer = Compress(buffer);
		string base64 = Convert.ToBase64String(compressBuffer);
		return base64;
	}

	public static string Decompress(string base64)
	{
		if (string.IsNullOrEmpty(base64))
			return base64;
		byte[] buffer = Convert.FromBase64String(base64);
		byte[] decompressBuffer = Decompress(buffer);
		string output = Encoding.UTF8.GetString(decompressBuffer);
		return output;
	}

	public static byte[] Compress(byte[] buffer)
	{
		if (buffer == null || buffer.Length == 0)
			return buffer;
		//将数据压缩到内存流中
		MemoryStream ms = new MemoryStream();
		GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true);
		gzip.Write(buffer, 0, buffer.Length);
		gzip.Flush();
		gzip.Close();
		gzip.Dispose();
		//从内存流中读出压缩数据
		byte[] compressBuffer = ms.ToArray();
		ms.Close();
		ms.Dispose();
		return compressBuffer;
	}

	public static byte[] Decompress(byte[] buffer)
	{
		if (buffer == null || buffer.Length == 0)
			return buffer;
		//将数据解压到内存流中
		MemoryStream ms = new MemoryStream(buffer);
		GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress, true);
		//从gzip流中读出解压数据
		buffer = new byte[buffer.Length];
		MemoryStream decompressStream = new MemoryStream();
		int count;
		while ((count = gzip.Read(buffer, 0, buffer.Length)) > 0)
			decompressStream.Write(buffer, 0, count);
		gzip.Close();

		byte[] decompressBuffer = decompressStream.ToArray();
		ms.Dispose();
		return decompressBuffer;
	}

	public static bool IsGZip(byte[] buffer)
	{
		//gzip头信息格式
		//ID1(1byte)+ID2(1byte)+压缩方法(1byte)+标志(1byte)+MTIME(4byte)+额外头字段(可选)
		//ID1和ID2为固定值ID1=31、ID2=139
		bool isgzip = true;
		byte[] head = new byte[] { 31, 139 };
		for (int i=0; i< head.Length; i++)
		{
			if (buffer[i] != head[i])
			{
				isgzip = false;
				break;
			}
		}
		return isgzip;
	}
}

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号