压缩Zip中的列表<img/>

时间:2017-06-28 23:10:37

标签: java image zip javax.imageio

我想把一个图像列表压缩成一个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)返回null。问题是什么?如果我先将图像保存在HDD中,并使用FileInputStream来读取文件,它会起作用吗?但我不想创建临时文件。

谢谢你的一切。

1 个答案:

答案 0 :(得分:3)

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

  

返回一个ImageInputStream,它将从给定的Object获取其输入。查询向IIORegistry类注册的ImageInputStreamSpis集合,并且第一个能够从提供的对象获取输入的集合用于创建返回的ImageInputStream。 如果不存在合适的ImageInputStreamSpi,则返回null。

  

input - 要用作输入源的Object,,例如File,可读RandomAccessFile或InputStream

(我强调的重点)

基本上,该方法需要FileInputStream,而不是Image。如果您将Image转换为RenderedImage(即BufferedImage),那么您只需使用ImageIO.write将图片直接写入ZipOutputStream

然后您的问题变为How to convert Image to BufferedImage in Java?