-1

I am tring to compress a list of Images into a single zip file.

public void compressZip(List<Image> lstImage) {
    //Abrimos una ventana JFileChooser
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int seleccion = fileChooser.showSaveDialog(laminaComicPrincipal);
    if (seleccion == JFileChooser.APPROVE_OPTION)
    {
       File fichero = fileChooser.getSelectedFile();
       try {
            ZipOutputStream os = new ZipOutputStream(new FileOutputStream(fichero.getAbsolutePath()+"file.zip"));
            int numeroImagen = 0;
            for(Image imagen: lstImage){

                ZipEntry entrada = new ZipEntry(numeroImagen+".jpg");
                os.putNextEntry(entrada);

                ImageInputStream fis = ImageIO.createImageInputStream(imagen);//THis sentences return null
                byte [] buffer = new byte[1024];
                int leido=0;
                while (0 < (leido=fis.read(buffer))){   //FAIL SENTENCES --> fis=null
                   os.write(buffer,0,leido);
                }

                fis.close();
                os.closeEntry();
                numeroImagen++;
            }
            os.close();
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    }

ImageIO.createImageInputStream(image n) returns null. What's the problem?? If I save the Images in HDD first, and use FileInputStream to read the files, will it work? but I prefer not to create temporally files.

Thank you for everything.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80

1 Answers1

3

If you have a look at the JavaDocs you will find your answers

Returns an ImageInputStream that will take its input from the given Object. The set of ImageInputStreamSpis registered with the IIORegistry class is queried and the first one that is able to take input from the supplied object is used to create the returned ImageInputStream. If no suitable ImageInputStreamSpi exists, null is returned.

And

input - an Object to be used as an input source, such as a File, readable RandomAccessFile, or InputStream.

(Emphasis added by me)

So basically, the method is expecting a File or InputStream, not an Image. If you convert your Image to RenderedImage (ie a BufferedImage), then you can just use ImageIO.write to write the image directly to the ZipOutputStream

Then your question becomes How to convert Image to BufferedImage in Java?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366