2013-01-03 174 views
3

我试图压缩png格式的图像序列。看来,压缩进展顺利:尝试压缩图像(Gzip + Jpeg),然后解压缩它们

FileOutputStream fos = null; 
GZIPOutputStream gzip = null; 
fos = new FileOutputStream(PATH_SAVE_GZIP); 
gzip = new GZIPOutputStream(fos); 
for (int i = 0; i < NB_OF_IMAGES; i++) { 
    BufferedImage im = images.get(i).getBufImg(); 
    ImageIO.write(im, "JPEG", gzip); 
} 
gzip.finish(); 
gzip.close(); 
fos.close(); 

但是我得到异常空指针...当我尝试用this代码进行解压缩。 我在做什么错了?

+0

Stacktrace请 –

+0

没有堆栈跟踪。我只是检查bi是否为空,它是在'BufferedImage bi = ImageIO.read(fin);' –

+0

之后看起来问题在于你将所有图像写入一个GZIP流,并且在阅读时不知道如何分裂,这是否与单一图像工作? –

回答

3

我已经完成了我的项目,现在我知道了答案。这可以通过几种方式解决:

一个是通过使用ObjectOutput/Input Stream并像对象一样写入BufferedImages。

另一种是使用ByteArrayOutputStream并写入像字节的图像。在使用此之前,您应该知道要写入的大小。所以我已经在每张图片之前解决了这个写作大小。没有效率的方式......但是有效。

 fileOutputStream fos = new FileOutputStream(path); 
     GZIPOutputStream gzip = new GZIPOutputStream(fos); 
     gzip.write(shortToBytes(numImatges)); 
     gzip.write(shortToBytes((short) 0));  
     for (int i = 0; i < dates.getNB_OF_IMAGES(); i++) { 

      if (images != null) { 
       im = images.get(i).getBufImg(); 
      } 
      ByteArrayOutputStream byteOstream = new ByteArrayOutputStream(); 
      ImageIO.write(im, "jpeg", byteOstream); 
      byteOstream.flush(); 
      byteOstream.close(); 
      gzip.write(shortToBytes((short) byteOstream.size())); 
      gzip.write(byteOstream.toByteArray()); 


      } 
//close streams 
0

你的问题是,你写的所有图像到一个GZIP流,当阅读时,ImageIO不知道一个图像结束和下一个开始。

你有两个选择:使用jtarJava Tar Package,然后GZIP焦油,看完你会先UnGZIP时再提取

  1. 使用ZIP,而不是GZIP
  2. 包中的文件在TAR文件来自tar文件的图像