我有一个流程,其中一些数据(比如图像/视频)使用GZip进行压缩,如下所示:
await using var outputStream = new MemoryStream();
await using var compressionStream = new GZipStream(outputStream, CompressionMode.Compress);
await compressionStream.WriteAsync(payload);
await compressionStream.FlushAsync();
outputStream.Position = 0;
return outputStream.ToArray()
上述代码不是来自我的团队,但如果需要可以进行更改。
如果我将输出转换为base64字符串并使用以下简单代码进行解压缩测试,则可以完美运行:
var bytes = Convert.FromBase64String("H4sIAAAAAAAACirOz01VKEmtKAEAAAD//w=="); // "some text"
using var ms = new MemoryStream(bytes);
using var ds = new GZipStream(ms, CompressionMode.Decompress);
using var output = new MemoryStream();
ds.CopyTo(output);
ds.Flush();
var result = output.ToArray();
然而,我的要求是在Python脚本中获取压缩的有效负载并在传递给另一个系统之前对其进行解压缩。我对Python一点也不熟悉,因此我编写了这个非常简单的脚本:
import base64
import gzip
encodedBase64 = "H4sIAAAAAAAACirOz01VKEmtKAEAAAD//w=="
decodedBytes = base64.standard_b64decode(encodedBase64)
decompressedBytes = gzip.decompress(decodedBytes)
以上内容出现了以下错误:
EOFError: Compressed file ended before the end-of-stream marker was reached
我当然进行了研究,找到了像这个Q&A之类的帖子,但没有什么帮助(例如,使用该答案会失败并显示gzip.BadGzipFile: Not a gzipped file (b'\x00\x00')
。其它尝试则产生不同的gzip错误。
decodedBytes
与bytes
),看看它们是否相同。 - canton7Flush
方法不会调用_deflater.Finish()
,但是Dispose
方法会调用。我猜这是有道理的——在压缩结束时需要添加一个页脚,而Flush
可能会被多次调用。 - canton7