DeflateStream无法使用从PHP实现处理的缓冲区 [英] DeflateStream not working with buffer processed from PHP implementation

查看:94
本文介绍了DeflateStream无法使用从PHP实现处理的缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解压缩由php deflate实现压缩的缓冲区。代码如下:

I'm trying to decompress buffer compressed by php deflate implementation. Here's the code:

    public static void CopyTo(Stream src, Stream dest)
    {
        byte[] bytes = new byte[4096];

        int cnt, i = 0;

        while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0 )
        {
            dest.Write(bytes, 0, cnt);
        }
        dest.Flush();
    }

    public static byte[] Unzip(byte[] bytes)
    {
        using (var msi = new MemoryStream(bytes))
        using (var mso = new MemoryStream())
        {
            using (var gs = new DeflateStream(msi, CompressionMode.Decompress))
            {

                msi.ReadByte();
                msi.ReadByte();
                CopyTo(gs, mso);
            }

            return mso.ToArray();
        }
    }

您注意到的是,我正在读取前2个字节从源流中获取,否则DeflateStream抛出异常,指出无效的块大小。但是,我的问题是,对于某些文件,此代码的工作方式像一个超级按钮,但是对于其他文件,却给出了损坏的结果(文件中只有一部分内容的文件。给人的印象是它没有对整个文件进行解压缩)。有人知道怎么了吗?

As you notice, I'm reading first 2 bytes from source stream, otherwise DeflateStream throws exception saying invalid block size. However, my problem is that, for some files, this code works like a charm, but for others, it gives corrupted result (a file with only some part of the file. Gives impression that it didn't decompress whole file). Anyone has any idea what's wrong?

谢谢

更新

我发现了用于压缩数据的PHP函数。它是 gzcompress

I found out PHP function used to compress the data. It's gzcompress.

推荐答案

您没有说您使用了什么php函数,但我猜是 gzcompress()。生成的zlib格式是原始deflate格式,并带有zlib标头和尾部,而 DeflateStream 期望没有标题或尾部的原始deflate。这就是为什么您必须跳过前两个字节,即zlib标头。

You didn't say what php function you used, but I'm guessing gzcompress(). That produces the zlib format which is the raw deflate format with a zlib header and trailer wrapped around it, whereas DeflateStream is expecting raw deflate with no header or trailer. That's why you're having to skip the first two bytes, which is the zlib header.

PHP函数名称很糟糕,令人困惑,文档也无济于事许多。这里有三种格式:原始deflate,gzip封装的deflate和zlib封装的deflate。所有PHP函数均以 gz 开头,但只有其中一些实际上处理gzip格式。

The PHP function names are terrible and confusing, and the documentation doesn't help much. There are three formats in play here: raw deflate, gzip-wrapped deflate, and zlib-wrapped deflate. All of the PHP functions start with gz but only some of them actually process the gzip format.

有时有效有时可能不是由于行尾或其他文字转换所致。确保您正在读取文件中的实际字节而没有损坏。

The sometimes working and sometimes not could be due to end-of-line or other text conversions. Make sure that you are reading the actual bytes in the file without corruption.

这篇关于DeflateStream无法使用从PHP实现处理的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆