SWT/AWT 容器or截屏导出到图片

本文介绍了如何使用SWT和AWT两种方法将容器或屏幕区域导出为图片。SWT方法利用Composite的print()方法,而AWT方法则通过Robot类获取屏幕捕获。两种方法分别适用于不同的场景,提供了灵活的截图导出解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
}
}

     这个方法可以导出任何区域,这个区域坐标是相对整个屏幕的绝对坐标。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值