使用zip压缩保存BufferedImage

时间:2013-04-07 02:13:14

标签: java zip bufferedimage

我如何将BufferedImage直接保存到zip文件中。

以下是我将BufferedImage保存为zip文件的当前代码,但我不知道如何将BufferedImage转换为InputStream,以便将其保存到zip文件中。

如果可能的话,我需要直接从RAM保存BufferedImage而不将其保存到HDD

byte[] buffer = new byte[1024];
try
{

    FileOutputStream outputStream = new FileOutputStream(PathName + imageData.getFileNumber() + ".zip");
    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
    ZipEntry imageZipOutput = new ZipEntry(imageData.getFileNumber() + ".png");
    zipOutputStream.putNextEntry(imageZipOutput);

    //the BufferedImage is stored in imageData.getImage();
    //how would I parse the BufferedImage to the InputStream below without saving the png first but straight from RAM
    InputStream in = new InputStream();

    int len;
    while ((len = in.read(buffer)) > 0)
    {
        zipOutputStream.write(buffer, 0, len);
    }

    in.close();
    zipOutputStream.closeEntry();

    zipOutputStream.close();

}

1 个答案:

答案 0 :(得分:3)

使用ImageIO.write(RenderedImage im,String formatName, OutputStream output)写入输出。为OutputStream参数传递ZipOutputStream

查看this页面了解更多信息。