0

I want to add a set of images to a ZIP file in C#. I use EmguCV to save the images. Currently I save the image locally first and then add to ZIP as follows.

Is there anyway to add the images to ZIP file directly on the fly without saving locally?

Sorry if this is a duplicate, I could not locate a clear answer for days.

using (FileStream zipToOpen = new FileStream(this.path, FileMode.Create))
{
  using (ZipArchive zipArchive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
  {
    for (int i = 0; i < clouds.Count; i++)
    {
      string imageCname = kinectId + "_" + dateTimes[i] + ".jpg";
      imageCt = imageCs[i];
      imageCt.Save("imageCt.jpg");
      zipArchive.CreateEntryFromFile(@"imageCt.jpg", imageCname);
      Console.WriteLine("Flushing rgb " + i + " of " + clouds.Count);
    }
  }
}

Update 1:

As suggested by #CarbineCoder I edited the code as follows. It saves a file. But cannot open as an image. I guess, it just save only the Byte steam. What else may I do to save it as a jpeg image.

string imageCname = kinectId + "_" + dateTimes[i] + ".jpg";
imageCt = imageCs[i];
ZipArchiveEntry zipEntryC = zipArchive.CreateEntry(imageCname);

using (var originalFileStream = new MemoryStream(imageCt.Bytes))
{
  using (var zipEntryStream = zipEntryC.Open())
  {
    originalFileStream.CopyTo(zipEntryStream);
  }
}
Huá dé ní 華得尼
  • 1,248
  • 1
  • 18
  • 33
  • Try these solutions - to use zipArchive.CreateEntry() - http://stackoverflow.com/questions/17232414/creating-a-zip-archive-in-memory-using-system-io-compression http://stackoverflow.com/questions/17217077/create-zip-file-from-byte – Carbine Feb 15 '16 at 05:40
  • @CarbineCoder, I edited the code as you suggested. It saves a file. But cannot open as an image. What may I doing wrong? I guess, I should specify the image format somewhere. – Huá dé ní 華得尼 Feb 15 '16 at 08:00

2 Answers2

1

Can you post the code you changed?

use zipArchive.CreateEntry() solutiuon specified in-

Create zip file from byte[]

Creating a ZIP Archive in Memory Using System.IO.Compression

Yes you might need to specify the extension of the file like zipArchive.CreateEntry("FileName.jpg"). This might solve your problem

Community
  • 1
  • 1
Carbine
  • 7,849
  • 4
  • 30
  • 54
0

Finally resolved the issue with the CarbineCoder suggestion. Posted below is the working code.

string imageCname = kinectId + "_" + dateTimes[i] + ".jpg";
imageCt = imageCs[i];

ZipArchiveEntry zipEntryC = zipArchive.CreateEntry(imageCname);

using (var stream = new MemoryStream())
{
  using (var zipEntryStream = zipEntryC.Open())
  {
    System.Drawing.Image userImage = imageCt.ToBitmap();
    userImage.Save(stream, ImageFormat.Jpeg);
    stream.Seek(0, SeekOrigin.Begin);
    stream.CopyTo(zipEntryStream);
  }
}
Console.WriteLine("Flushing rgb " + i + " of " + clouds.Count);
Huá dé ní 華得尼
  • 1,248
  • 1
  • 18
  • 33