在 Zip 中压缩列表<Image>

Compress List<Image> in a Zip

我正在尝试将图像列表压缩到一个 zip 文件中。

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)returnsnull。有什么问题??如果我先把图片存到硬盘里,然后用FileInputStream读取文件,可以吗?但我不想创建临时文件。

谢谢你所做的一切。

如果您查看 JavaDocs 您会找到答案

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.

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

(重点是我加的)

所以基本上,该方法需要 FileInputStream,而不是 Image。如果你把你的Image转换成RenderedImage(即一个BufferedImage),那么你可以直接用ImageIO.write把图像直接写到ZipOutputStream

那么你的问题就变成了