我正在寻找c#中的LZW压缩算法,可以压缩和解压缩word文档。我已经在谷歌上搜索过了,但没有给出我需要的答案。谁能帮助我有它的代码,让我了解如何真正实现LZW在我的项目中。
发布于 2016-01-28 16:21:06
下面是我在项目中使用的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();
}
}
}发布于 2012-01-03 22:39:46
有一个实现here。
LZW并不关心它使用的是什么类型的文件。每个文件都被视为字节的blob。
发布于 2012-01-03 22:42:27
一种线性零树变换的c#实现:http://code.google.com/p/sharp-lzw/
https://stackoverflow.com/questions/8713850
复制相似问题