GZipStream and decompression

最后都变了- 提交于 2019-11-28 09:58:50

My first thought is that you haven't closed csStream. If you use using this happens automatically. Since gzip buffers data, you could be missing some.

Secondly; don't increment offset; that is the offset in the buffer (not the stream). Leave at 0:

using (Stream fs = File.OpenRead("gj.txt"))
using (Stream fd = File.Create("gj.zip"))
using (Stream csStream = new GZipStream(fd, CompressionMode.Compress))
{
    byte[] buffer = new byte[1024];
    int nRead;
    while ((nRead = fs.Read(buffer, 0, buffer.Length))> 0)
    {
        csStream.Write(buffer, 0, nRead);
    }
}

using (Stream fd = File.Create("gj.new.txt"))
using (Stream fs = File.OpenRead("gj.zip"))
using (Stream csStream = new GZipStream(fs, CompressionMode.Decompress))
{
    byte[] buffer = new byte[1024];
    int nRead;
    while ((nRead = csStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fd.Write(buffer, 0, nRead);
    }
}

The two methods I have are like James Roland mentioned.

private static byte[] Compress(HttpPostedFileBase file)
{
    var to = new MemoryStream();
    var from = new GZipStream(to, CompressionMode.Compress);
    file.InputStream.CopyTo(from);
    from.Close();
    return to.ToArray();
}

private byte[] Decompress(byte [] img)
{
    var to = new MemoryStream();
    var from = new MemoryStream(img);
    var compress = new GZipStream(from, CompressionMode.Decompress);
    compress.CopyTo(to);
    from.Close();
    return to.ToArray();
}

However, I'm using an upload with

Request.Files[0] 

then compress and save in the db. Then I pull the img out, decompress and set a src with

$"data:image/gif;base64,{ToBase64String(Decompress(img))}";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!