2019-07-21 16:29

C# 用 gzip 壓縮字串並取得 base64 字串

這個使用方式的效果是有但書的,當 Source 的重複率不高壓縮的效果就不會好,再加上 base64 就是用可見文字去表示 byte 值,這會讓 base64 後的結果比 byte array 還要長,所以壓縮率沒有到達一定的程度下,輸出反而會比 Source 的字串還要長。

//using System.IO.Compression;


void Main()
{
    string text = "OptionPostal,OptionClassType,OptionTalentItem";
    text.Length.Dump(); /* 45 */

    string compressBase64 = compress(text);
    compressBase64.Length.Dump(); /* 76 */
    compressBase64.Dump(); 
    /* H4sIAAAAAAAEAPMvKMnMzwvILy5JzNHxB3OccxKLi0MqC1Kh/JDEnNS8Es+S1FwAaY6qVC0AAAA= */

    string decompressText = decompress(compressBase64);
    decompressText.Dump(); 
    /* OptionPostal,OptionClassType,OptionTalentItem */

    text = "OptionPostal,OptionClassType,OptionTalentItem,OptionPostal,OptionClassType,OptionTalentItem,OptionPostal,OptionClassType,OptionTalentItem,OptionPostal,OptionClassType,OptionTalentItem";
    text.Length.Dump(); /* 183 */

    compressBase64 = compress(text);
    compressBase64.Length.Dump(); /* 84 */
    compressBase64.Dump(); 
    /* H4sIAAAAAAAEAPMvKMnMzwvILy5JzNHxB3OccxKLi0MqC1Kh/JDEnNS8Es+S1FyowCBQDQBPmlWktwAAAA== */

}


/*壓縮*/
private static string compress(string text)
{
    if (string.IsNullOrEmpty(text)) { return text; }

    byte[] buffer = Encoding.UTF8.GetBytes(text);

    using (var outStream = new MemoryStream())
    using (var zip = new GZipStream(outStream, CompressionMode.Compress))
    {
        zip.Write(buffer, 0, buffer.Length);
        zip.Close();

        string compressedBase64 = Convert.ToBase64String(outStream.ToArray());
        return compressedBase64;
    }
}


/*解壓縮*/
private static string decompress(string compressed)
{
    if (string.IsNullOrEmpty(compressed)) { return compressed; }

    byte[] buffer = Convert.FromBase64String(compressed);

    using (var inStream = new MemoryStream(buffer))
    using (var outStream = new MemoryStream())
    using (var zip = new GZipStream(inStream, CompressionMode.Decompress))
    {
        zip.CopyTo(outStream);
        zip.Close();

        string text = Encoding.UTF8.GetString(outStream.ToArray());
        return text;
    }
}

0 回應: