GZipStream不压缩? [英] GZipStream not compressing?

查看:258
本文介绍了GZipStream不压缩?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个内存流压缩到另一个内存流,所以我可以上传到一个rest API。 image 是包含tif图片的初始内存流。

I'm trying to zip a memory stream into another memory stream so I can upload to a rest API. image is the initial memory stream containing a tif image.

WebRequest request = CreateWebRequest(...);
request.ContentType = "application/zip";
MemoryStream zip = new MemoryStream();
GZipStream zipper = new GZipStream(zip, CompressionMode.Compress);
image.CopyTo(zipper);
zipper.Flush();
request.ContentLength = zip.Length; // zip.Length is returning 0
Stream reqStream = request.GetRequestStream();
zip.CopyTo(reqStream);
request.GetResponse().Close();
zip.Close();

据我所知,任何写入GZipStream的东西都会被压缩并写入任何流它的构造函数。当我将图像流复制到拉链,它似乎没有什么是实际复制(图像是200+ MB)。这是我第一次使用GZipStream的经验,所以很可能我错过了一些东西,任何关于什么会非常感激的建议。

To my understand, anything I write to the GZipStream will be compressed and written to whatever stream was passed into it's constructor. When I copy the image stream into zipper, it appears nothing is actually copied (image is 200+ MB). This is my first experience with GZipStream so it's likely I'm missing something, any advice as to what would be greatly appreciated.

编辑:
注意对我来说是一个问题,在上面的代码中, image 的位置是在流的结尾...因此,当我调用

Something I should note that was a problem for me, in the above code, image's position was at the very end of the stream... Thus when I called image.CopyTo(zipper); nothing was copied due to the position.

推荐答案

:删除GZipStream上不正确的信息及其构造函数args,并使用真实答案更新:)]

复制到拉链,你需要将MemoryStream的位置移回到零,因为拉链写入内存流的过程推进它的游标以及正在读取的流:

After you've copied to the zipper, you need to shift the position of the MemoryStream back to zero, as the process of the zipper writing to the memory stream advances it's "cursor" as well as the stream being read:

WebRequest request = CreateWebRequest(...);
request.ContentType = "application/zip";
MemoryStream zip = new MemoryStream();
GZipStream zipper = new GZipStream(zip, CompressionMode.Compress);
image.CopyTo(zipper);
zipper.Flush();
zip.Position = 0; // reset the zip position as this will have advanced when written to.
...

另外要注意的一点是,GZipStream不可搜索调用.Length将抛出异常。

One other thing to note is that the GZipStream is not seekable, so calling .Length will throw an exception.

这篇关于GZipStream不压缩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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