【发布时间】:2013-08-23 15:06:31
【问题描述】:
我在内存中生成了许多 BufferedImage,我想将它们压缩成一个 zip 文件,然后再将其作为电子邮件附件发送。如何在不从磁盘读取文件的情况下将文件保存到 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。
-
只是出于好奇,您为什么要避免创建临时文件?
-
您可以写入流而不是文件,但您始终必须能够读取原始文件数据。但是,我认为源文件也可以是流。
-
你使用什么样的文件句柄来引用内存中的那些pdf文件?文件?文件输入流?
标签: java