LZW数据压缩
本文关键字:压缩 数据 LZW | 更新日期: 2023-09-27 18:19:15
我正在寻找c#中的LZW压缩算法,可以压缩和解压缩word文档。我在谷歌上搜索过,但它没有给我想要的答案。谁能帮助我有它的代码,让我了解如何真正实现LZW在我的项目。
这里有一个实现。
LZW不关心它正在处理什么类型的文件。
这是我在我的项目中使用的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();
}
}
}
如果有人碰到这个…我在Mark Nelson的github网站上找到了一篇文章中描述的算法的c#实现,在这里:
https://github.com/pevillarreal/LzwCompressor就我个人而言,我进一步调整代码以使用MemoryStream
而不是FileStream
,因为我需要转换字节数组,而不是保存的文件,但这种更改非常微不足道。
LZW的c#实现:http://code.google.com/p/sharp-lzw/