'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?
Solution 1:[1]
Your ZipArchive is mapped onto a MemoryStream (variable ms
). You can get the contents of a MemoryStream as a byte array using MemoryStream.ToArray().
Solution 2:[2]
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");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Paul-Jan |
Solution 2 | Mohammed Osman |