2

如何使用 DotNetZip ZipEntry 类在 WPF 中加载图像。

using (ZipFile file = ZipFile.Read ("Images.zip"))
{
    ZipEntry entry = file["Image.png"];
    uiImage.Source = ??
}
4

2 回答 2

0

您可能会使用 a BitmapSource,但原始图像数据仍需要解压缩,我不确定是否以您实际动态解压缩的方式打开 zip 以便或不这样做;但是一旦你有了它,你应该能够执行以下操作:

BitmapSource bitmap = BitmapSource.Create(
    width, height, 96, 96, pf, null, rawImage, rawStride);

rawImage数组形式的图像文件的字节在哪里。其他参数包括您现在应该或能够确定的 DPI 和像素格式。

为了获取该rawStride值,MSDN 有以下示例作为示例:

PixelFormat pf = PixelFormats.Bgr32;
int rawStride = (width * pf.BitsPerPixel + 7) / 8;
于 2011-08-18T09:30:26.847 回答
0

ZipEntry 类型公开了一个返回可读流的 OpenReader() 方法。这可能对您有用:

// I don't know how to initialize these things
BitmapImage image = new BitmapImage(...?...);
ZipEntry entry = file["Image.png"];
image.StreamSource = entry.OpenReader(); 

我不确定这会起作用,因为:

  • 我不知道 BitmapImage 类或如何管理它,或者如何从流中创建一个。我那里的代码可能有误。

  • ZipEntry.OpenReader() 方法在内部设置和使用由 ZipFile 实例管理的文件指针,并且可读流仅在 ZipFile 实例本身的生命周期内有效。
    ZipEntry.OpenReader() 返回的流必须在任何后续调用 ZipEntry.OpenReader() 以获取其他条目之前以及 ZipFile 超出范围之前读取。如果您需要从一个 zip 文件中提取和读取多个图像,没有特定的顺序,或者您需要在完成 ZipFile 后阅读,那么您需要解决这个限制。为此,您可以调用 OpenReader() 并将每个特定条目的所有字节读取到不同的 MemoryStream 中。

像这样的东西:

  using (ZipFile file = ZipFile.Read ("Images.zip"))        
  {        
      ZipEntry entry = file["Image.png"];
      uiImage.StreamSource = MemoryStreamForZipEntry(entry);        
  } 

 ....

private Stream MemoryStreamForZipEntry(ZipEntry entry) 
{
     var s = entry.OpenReader();
     var ms = new MemoryStream(entry.UncompressedSize);
     int n; 
     var buffer = new byte[1024];
     while ((n= s.Read(buffer,0,buffer.Length)) > 0) 
         ms.Write(buffer,0,n);
     ms.Seek(0, SeekOrigin.Begin);
     return ms;
}
于 2011-08-21T14:07:02.580 回答