简体   繁体   中英

How do I add a byte array Image to a ziparchive?

My situation: I have a bunch of Jpeg images in the form of byte arrays. I have a list of these objects:

public class MyImage
{
    public byte[] ImageData { get; set; }
}

My desired situation: I want to create a zip file in memory and put it in a variable. I am creating these zip files in a REST service. Ideally, I would turn this ziparchive into a byte array so that I can send it to systems written in other languages.

I have code for creating a ziparchive, and adding my image byte arrays to it. But how do I turn the ziparchive itself into a byte array?

var images = new List<MyImage>();

//add data to images 

using (var ms = new MemoryStream())
{
    using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, true))
    {
        var i = 1;
        foreach (var image in images)
        {
            var entry = zipArchive.CreateEntry("image" + i + ".jpg", CompressionLevel.Fastest);
            using (var entryStream = entry.Open())
            {
                entryStream.Write(image.ImageData, 0, photo.ImageOriginal.Length);
            }
            i++;
        }

        //var zipBytes = magic method for turning my archive into a zipfile
    }
}

My question: How do I get this to work? Bonus question: is a ziparchive turned into a byte array compatible with other languages?

Your ZipArchive is mapped onto a MemoryStream (variable ms ). You can get the contents of a MemoryStream as a byte array using MemoryStream.ToArray() .

To convert memory stream array to a zip file, you can use a method such that:

var file = File(ms.ToArray(), "application/zip", "zipFileName.zip");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM