zlib.Net的压缩和解压缩问题
本文关键字:解压缩 问题 压缩 Net zlib | 更新日期: 2023-09-27 18:01:27
我正在使用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"
。
感谢用户@longbkit提供的参考答案(由@JoshStribling提供),帮助我解决了这个问题。
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构造函数…
神奇。对我来说,如果压缩被称为输出,而解压-输入会更清楚。或者这样的…
更改代码
inZStream.Read
- ->inZStream.read
from sourceCode in ZInputStream.cs