1、SWT导出图片
/**
* 输出容器到图片方法
*
* @param com
* 要导出的容器
* @param path
* 导出路径
* @param pathType
* 图片格式 如:SWT.IMAGE_JPEG
*/
public static void paintImageSWT(Composite com, String path, int pathType) {
Rectangle rect = com.getClientArea();
Image image = new Image(Display.getCurrent(), rect.width, rect.height);
com.print(new GC(image));
ImageLoader loader = new ImageLoader();
loader.data = new ImageData[] { image.getImageData() };
loader.save(path, pathType);
}
构造一个Image,重点使用了 Composite的print()方法。
注:要导出的必须是个容器内的区域。
2、AWT的方法。
/**
* AWT方式导出图片
*
* @param path
* 导出图片的路径
* @param shell
* 容器窗口
* @param com
* 导出的容器
*/
public static void paintImageAWT(String path, Shell shell, Composite com) {
Robot robot;
Rectangle comRect = com.getBounds();
Point point = shell.toDisplay(comRect.x, comRect.y);
try {
robot = new Robot();
java.awt.Rectangle rect = new java.awt.Rectangle(point.x, point.y,
comRect.width, comRect.height);
BufferedImage image = robot.createScreenCapture(rect);
File imageFile = new File(path);
String postfix = path.substring(path.lastIndexOf(".") + 1);
ImageIO.write(image, postfix, imageFile);
} catch (Exception e) {
e.printStackTrace();
}
}
这个方法可以导出任何区域,这个区域坐标是相对整个屏幕的绝对坐标。