【问题标题】:How to Zip a MemoryStream of an image如何压缩图像的 MemoryStream
【发布时间】:2017-04-21 13:36:50
【问题描述】:

我有一个图像的字节数组,我想从中创建 Zip 文件。

我可以成功地将字节数组保存在jpg文件中,但是当我从中创建zip文件时,zip文件的图像(zip文件中的图像)被损坏并且我无法打开它! (当我尝试打开图像时,Winrar 显示以下错误消息: D:\sample.zip:存档格式未知或已损坏 )

注意:我的图像在内存中,我不想创建物理图像文件。

这是我的代码:

private void Zip(byte[] imageBytes)
{
    string filePath = string.Empty;
    using (var ms = new MemoryStream())
    using (var zip = new ZipArchive(ms, ZipArchiveMode.Create))
    {
        var entry = zip.CreateEntry("sample.jpg", CompressionLevel.Optimal);

        using (var entryStream = entry.Open())
        using (var fileToCompressStream = new MemoryStream(imageBytes))
        {
            fileToCompressStream.CopyTo(entryStream);
        }

        using (var fs = new FileStream(baseFilePath + "sample.zip", FileMode.Create))
        {
            ms.Position = 0;
            ms.WriteTo(fs);
        }
    }
}

【问题讨论】:

  • 我还从 imageBytes(参数)创建了新的 Bitmap 实例并将其保存到 entryStream,但同样的问题!

标签: c# arrays image zip memorystream


【解决方案1】:

你应该能够做到:

using System.IO;
using System.IO.Compression;
using System.Text;

private void Zip (byte[] imageBytes) {

 string fileName = baseFilePath + "sample.zip";
 using (FileStream f2 = new FileStream(fileName, FileMode.Create)){
        using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
        {
            gz.Write(imageBytes, 0, imageBytes.Length);
        }
   }
}

【讨论】:

  • 它工作正常。谢谢。如何设置图像文件的名称? (它以相同名称的 zip 文件保存,没有任何扩展名)
  • 我认为,GZip 不适合我的情况,因为我最终需要将多张图像放入一个 zip 文件中,据我所知,GZipStream 只适合压缩一个文件。我说的对吗?
  • 您在此处正确阅读了如何处理多个文件:stackoverflow.com/questions/24571773/…
  • SharpZipLib 是非常有用的库。 (nuget.org/packages/SharpZipLib)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 2016-01-29
相关资源
最近更新 更多