使用BufferedImage生成图片
保存图片有两种方式:
1.JPEGImageEncoder
该种方式保存的图片会失真,而且图片还大,不建议使用;
BufferedImage image;
BufferedOutputStream bos = null;
if (image != null) {
try {
FileOutputStream fos = new FileOutputStream("E:\\testPic.png");
bos = new BufferedOutputStream(fos);
// image.getGraphics().drawImage(
// image.getScaledInstance(imageWidth, imageHeight,java.awt.Image.SCALE_SMOOTH), 0, 0, null);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
bos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {// 关闭输出流
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

2.使用ImageIO保存图片
推荐使用,图片精度高,size小;
// 得到图形对象
Graphics2D g2d = image.createGraphics();
// 将窗口内容面板输出到图形对象中
// content.printAll(g2d);
// 保存为图片
File f = new File("E:\\testPic.png");
try {
ImageIO.write(image, "png", f);
} catch (IOException e) {
e.printStackTrace();
}
// 释放图形对象
g2d.dispose();

网友评论