简体   繁体   中英

Create Zip file for multiple images c#

In my requirement I am converting docx to images its working fine but I need to store that converted multiple images into Zip file. Zip file was created successfully but Images are not opening it show corrupted/damage. Please try to help me to solve this solution. please refer my below total code. I used using Ionic.Zip; for creating a zip file.

         //Opens the word document and fetch each page and converts to image
        foreach (Microsoft.Office.Interop.Word.Window window in doc1.Windows)
        {
            foreach (Microsoft.Office.Interop.Word.Pane pane in window.Panes)
            {
                using (var zip = new ZipFile())
                {
                    var pngTarget = "";
                    for (var i = 1; i <= pane.Pages.Count; i++)
                    {
                        var page = pane.Pages[i];
                        var bits = page.EnhMetaFileBits;
                        var target = Path.Combine(startupPath.Split('.')[0], string.Format("{1}_page_{0}", i, startupPath.Split('.')[0]));

                        try
                        {
                            using (var ms = new MemoryStream((byte[])(bits)))
                            {
                                var image = System.Drawing.Image.FromStream(ms);
                                pngTarget = Path.ChangeExtension(target, "png");
                                image.Save(pngTarget, ImageFormat.Png);
                                zip.AddEntry(pngTarget, "Img");
                            }
                        }
                        catch (System.Exception ex)
                        { }
                    }

                    // CREATE A FILE USING A STRING. 
                    // THE FILE WILL BE STORED INSIDE THE ZIP FILE.


                    // ZIP THE FOLDER WITH THE FILES IN IT.
                    //zip.AddFiles(Directory.GetFiles(@"c:\\users\\chaitanya_t\\Downloads\\"), "Images");

                    zip.Save(@"c:\\users\\chaitanya_t\\Downloads\\encoded.zip");  // SAVE THE ZIP FILE.
                }


            }
        }

Try setting the stream position at the begin of the stream before processing:

using (var ms = new MemoryStream((byte[])(bits))){
 ms.Position = 0; // Set stream position at the begin of the stream
 var image = System.Drawing.Image.FromStream(ms);
 pngTarget = Path.ChangeExtension(target, "png");
 image.Save(pngTarget, ImageFormat.Png);
 zip.AddEntry(pngTarget, ms.ToArray());
}

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