3

I am trying to compress a sequence of images in png format. It seems that compression is going well:

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();

However I get Exception Nullpointer... when I try to uncompress it with this code. What am I'm doing wrong?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Vito Valov
  • 1,765
  • 1
  • 19
  • 37
  • there's no stacktrace. I just check if bi is null, and it is after `BufferedImage bi = ImageIO.read(fin);` – Vito Valov Jan 05 '13 at 18:39
  • It seems the problem is that you write all of the images to one GZIP stream and when reading it doesn't know how to split, does this work with a single image ? – Aviram Segal Jan 09 '13 at 20:08
  • Yes it works with single. I think this is because ImageIO doesn't write separators. So when reading it doesn't know where to finishes one image and starts another – Vito Valov Jan 09 '13 at 20:15
  • You must somehow join them before using GZIP, or just uze ZIP which you can have an entry for each file – Aviram Segal Jan 10 '13 at 07:52
  • I need to use GZIP, this's requirement. How to perform this? – Vito Valov Jan 10 '13 at 08:50

2 Answers2

3

I've finished my project and now I know the answer. This could be solved by several ways:

One is by using ObjectOutput/Input Stream and write BufferedImages like objects.

The other is to use ByteArrayOutputStream and write images like bytes. Prior to use this you should know the size to be written. So I've solved this writing size before each image. Not efficient way... However works.

        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
Vito Valov
  • 1,765
  • 1
  • 19
  • 37
0

Your problem is that you write all the images to a single GZIP stream and when reading, ImageIO doesn't know where one image ends and the next begins.

You got two options:

  1. Use ZIP instead of GZIP
  2. Package the files in a TAR file using jtar or Java Tar Package and then GZIP the tar, when reading you will first UnGZIP and then extract the images from the tar file
Aviram Segal
  • 10,962
  • 3
  • 39
  • 52