2011-08-18 26 views
2

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

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

什么的UIImage?什么类型的? – Cheeso

+0

它的类型图像。 – Dave

回答

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; 
} 
0

你可能会使用一个BitmapSource,但原始图像数据将仍然需要进行解压缩,我不知道如果打开的方式,你实际上做的拉链上飞解压缩,这样,或不;但一旦你有,你应该能够做到像下面这样:

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

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

为了得到rawStride值,MSDN has the following sample作为一个例子:

PixelFormat pf = PixelFormats.Bgr32; 
int rawStride = (width * pf.BitsPerPixel + 7)/8;