我已經在內存中生成了許多BufferedImages,我想在將它們作爲電子郵件附件發送之前將它們壓縮到一個zip文件中。如何在不從磁盤讀取文件的情況下將文件保存爲zip文件。如何在不保存到Java磁盤的情況下生成zip文件?
有什麼辦法可以壓縮這些文件而不創建臨時文件?
由於創建了數千個文件,寫入磁盤非常耗時。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cccprog;
import java.awt.Component;
import java.awt.Panel;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
/**
*
* @author Z
*/
public class N {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
JFrame jf = new JFrame();
Panel a = new Panel();
JRadioButton birdButton = new JRadioButton();
birdButton.setSize(100, 100);
birdButton.setSelected(true);
jf.add(birdButton);
getSaveSnapShot(birdButton, i + ".bmp");
}
}
public static BufferedImage getScreenShot(Component component) {
BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
// paints into image's Graphics
component.paint(image.getGraphics());
return image;
}
public static void getSaveSnapShot(Component component, String fileName) throws Exception {
BufferedImage img = getScreenShot(component);
// BufferedImage img = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
// write the captured image as a bmp
ImageIO.write(img, "bmp", new File(fileName));
}
}
看看java.utli.zip。 –
爲了我的好奇心,爲什麼要避免創建臨時文件? – 2013-08-23 15:09:39
這似乎相關http://stackoverflow.com/questions/7108035/how-to-flush-the-zipoutputstream-periodically-in-java – Ted