我正在使用ZLIB.Net,我只是不明白我应该怎样做来压缩不是FileStream
的流,而是MemoryStream
。通过做:
byte[] buffer = ASCIIEncoding.ASCII.GetBytes("Hello World");
MemoryStream outStream = new MemoryStream();
zlib.ZOutputStream outZStream = new zlib.ZOutputStream(
outStream,
zlib.zlibConst.Z_BEST_COMPRESSION);
outZStream.Write(buffer, 0, buffer.Length);
outZStream.finish();
buffer = outStream.GetBuffer();
Debug.WriteLine(DateTime.Now.ToString() + ":" + buffer.Length);
MemoryStream inStream = new MemoryStream(buffer);
MemoryStream mo = new MemoryStream();
zlib.ZInputStream inZStream = new zlib.ZInputStream(
inStream,
zlib.zlibConst.Z_BEST_COMPRESSION);
int n = 0;
while ((n = inZStream.Read(buffer, 0, buffer.Length)) > 0)
{
mo.Write(buffer, 0, n);
}
string STR = ASCIIEncoding.ASCII.GetString(mo.GetBuffer());
我无法恢复字符串"Hello World"
。
答案 0 :(得分:9)
longbkit ,感谢您的参考。 那里有代码:
public static void CompressData(byte[] inData, out byte[] outData)
{
using (MemoryStream outMemoryStream = new MemoryStream())
using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream, zlibConst.Z_DEFAULT_COMPRESSION))
using (Stream inMemoryStream = new MemoryStream(inData))
{
CopyStream(inMemoryStream, outZStream);
outZStream.finish();
outData = outMemoryStream.ToArray();
}
}
public static void DecompressData(byte[] inData, out byte[] outData)
{
using (MemoryStream outMemoryStream = new MemoryStream())
using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream))
using (Stream inMemoryStream = new MemoryStream(inData))
{
CopyStream(inMemoryStream, outZStream);
outZStream.finish();
outData = outMemoryStream.ToArray();
}
}
public static void CopyStream(System.IO.Stream input, System.IO.Stream output)
{
byte[] buffer = new byte[2000];
int len;
while ((len = input.Read(buffer, 0, 2000)) > 0)
{
output.Write(buffer, 0, len);
}
output.Flush();
}
有效。 但我所看到的是压缩和解压缩之间唯一的差异是ZOutput构造函数中的压缩类型......
惊人。如果Compression在减压 - 输入时称为输出,那么对我来说会更清楚。或者这样......实际上它只是输出。
❋ 用户“John Smith”破坏了原始代码,因为CopyTo不起作用并在其编辑的文本中引发异常(并且被其他人批准两次......)。 通过OP恢复原始代码示例。 请在下次编辑之前测试编辑过的代码,谢谢。
答案 1 :(得分:1)
更改代码。
inZStream.Read
-> inZStream.read
来自ZInputStream.cs中的sourceCode