为多个图像创建Zip文件c#

问题描述 投票:0回答:1

根据我的要求,我将docx转换为图像工作正常,但我需要将转换后的多个图像存储到Zip文件中。 Zip文件已成功创建但图像未打开它显示已损坏/损坏。请尽量帮我解决这个问题。请参考下面的总代码。我用过Ionic.Zip;用于创建zip文件。

         //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.
                }


            }
        }
c# asp.net .net zip
1个回答
1
投票

尝试在处理之前在流的开头设置流位置:

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());
}
© www.soinside.com 2019 - 2024. All rights reserved.