2012-01-03 132 views
0

我正在尋找可以壓縮和解壓縮Word文檔的C#中的LZW壓縮算法。我在谷歌搜索它,但它沒有給我我需要的答案。任何人都可以幫助我獲得它的代碼,並讓我瞭解如何在我的項目中真正實現LZW。LZW數據壓縮

+3

你需要使用LZW而不是GZip的任何理由? – 2012-01-03 14:37:44

+1

可能[重複](http://stackoverflow.com/questions/6710014/lzw-compression-on-c-sharp-from-string) – 2012-01-03 14:42:30

+0

我會問同樣的 - 具體使用LZW的原因是什麼?您是否在與使用LZW的其他系統交互時嘗試進行壓縮/解壓縮?如果是這樣,則用戶發佈的實現可能與您的外部系統不兼容。請澄清這個問題。祝好, – 2012-01-03 14:47:51

回答

4

有一個實現here

LZW不關心它使用的文件類型。每個文件都被視爲一個字節塊。

+0

感謝您的幫助。 – Eric 2012-01-03 14:42:57

+1

這是一個奇怪而可怕的實現......它將值作爲二進制字符串輸出。 – Nyerguds 2017-07-29 14:06:32

1

下面是我在我的項目中使用的LZW的實施:

namespace LZW 
{ 
    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      List<int> compressed = Compress("string to be compressed"); 
      Console.WriteLine(string.Join(", ", compressed)); 
      string decompressed = Decompress(compressed); 
      Console.WriteLine(decompressed); 
     } 

     public static List<int> Compress(string uncompressed) 
     { 
      // build the dictionary 
      Dictionary<string, int> dictionary = new Dictionary<string, int>(); 
      for (int i = 0; i < 256; i++) 
       dictionary.Add(((char)i).ToString(), i); 

      string w = string.Empty; 
      List<int> compressed = new List<int>(); 

      foreach (char c in uncompressed) 
      { 
       string wc = w + c; 
       if (dictionary.ContainsKey(wc)) 
       { 
        w = wc; 
       } 
       else 
       { 
        // write w to output 
        compressed.Add(dictionary[w]); 
        // wc is a new sequence; add it to the dictionary 
        dictionary.Add(wc, dictionary.Count); 
        w = c.ToString(); 
       } 
      } 

      // write remaining output if necessary 
      if (!string.IsNullOrEmpty(w)) 
       compressed.Add(dictionary[w]); 

      return compressed; 
     } 

     public static string Decompress(List<int> compressed) 
     { 
      // build the dictionary 
      Dictionary<int, string> dictionary = new Dictionary<int, string>(); 
      for (int i = 0; i < 256; i++) 
       dictionary.Add(i, ((char)i).ToString()); 

      string w = dictionary[compressed[0]]; 
      compressed.RemoveAt(0); 
      StringBuilder decompressed = new StringBuilder(w); 

      foreach (int k in compressed) 
      { 
       string entry = null; 
       if (dictionary.ContainsKey(k)) 
        entry = dictionary[k]; 
       else if (k == dictionary.Count) 
        entry = w + w[0]; 

       decompressed.Append(entry); 

       // new sequence; add it to the dictionary 
       dictionary.Add(dictionary.Count, w + entry[0]); 

       w = entry; 
      } 

      return decompressed.ToString(); 
     } 
    } 
} 
+0

但是,爲什麼要使用列表而不是字節數組?另外,呃,它不僅僅是用於字符串...... – Nyerguds 2017-07-11 11:59:06

+0

它不僅僅是用於字符串。 ?你試圖達到什麼樣的目的,你可以根據你的需求修改它,你也可以修改它來使用字節數組,而不是int,這只是一個示例。切記疊加流程僅供參考,並非編碼服務:) – csharpcoder 2017-07-12 03:44:56

+0

LZW還用於非文本數據壓縮。但是真的很難找到這樣的例子:(至於我想要達到的目標,我正在研究在二進制文件存儲中使用LZW的舊DOS遊戲的修改工具。 – Nyerguds 2017-07-13 10:11:28