Search code examples
c#arraysimagezipmemorystream

How to Zip a MemoryStream of an image


I have byte array of an image, I want to create Zip file from it.

I can save the byte array in jpg file successfully, But when I create zip file from it, the image of the zip file (the image that is into the zip file) was damaged and I Can't open it! (when I try to open the image, Winrar display error message bellow: D:\sample.zip: The archive is either in unknown format or damaged )

Note: My image is in memory and I don't want to create physically image file.

Here is my codes:

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);
        }
    }
}

Solution

  • You should be able to just do:

    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);
            }
       }
    }