【问题标题】:Compress List<Image> in a Zip在 Zip 中压缩 List<Image>
【发布时间】:2017-06-28 23:10:36
【问题描述】:

我正在尝试将图像列表压缩到单个 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。有什么问题??如果我先将图像保存在硬盘中,然后使用FileInputStream 读取文件,它会工作吗?但我不喜欢创建临时文件。

谢谢你所做的一切。

【问题讨论】:

    标签: java image zip javax.imageio


    【解决方案1】:

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

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

    input - 用作输入源的对象,例如 File、可读的 RandomAccessFile 或 InputStream

    (我添加的重点)

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

    那么你的问题就变成How to convert Image to BufferedImage in Java?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多