为多个图像创建Zip文件c#
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为多个图像创建Zip文件c#相关的知识,希望对你有一定的参考价值。
根据我的要求,我将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.
}
}
}
答案
尝试在处理之前在流的开头设置流位置:
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());
}
以上是关于为多个图像创建Zip文件c#的主要内容,如果未能解决你的问题,请参考以下文章
Laravel 8,为公共文件夹中的所有图像创建 zip 文件。面对文件错误:ZipArchive::addFile(): Invalid or uninitialized Zip object