Java实现屏幕截图及剪裁

本文介绍了如何使用Java的Robot类进行屏幕截图,包括创建指定区域的截图以及后续的剪裁操作,同时提供了将截图保存为文件的方法。
摘要由CSDN通过智能技术生成

Java实现屏幕截图及剪裁

 java标准API中有个Robot类,该类可以实现屏幕截图,模拟鼠标键盘操作这些功能。这里只展示其屏幕截图。

截图的关键方法createScreenCapture(Rectangle rect) ,该方法需要一个Rectangle对象,Rectangle就是定义屏幕的一块矩形区域,构造Rectangle也相当容易:

new Rectangle(int x, int y, int width, int height),四个参数分别是矩形左上角x坐标,矩形左上角y坐标,矩形宽度,矩形高度。截图方法返回BufferedImage对象,示例代码:

/**

* 指定屏幕区域截图,返回截图的BufferedImage对象

* @param x

* @param y

* @param width

* @param height

* @return

*/

public BufferedImage getScreenShot(int x, int y, int width, int height) {

BufferedImage bfImage = null;

try {

Robot robot = new Robot();

bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));

} catch (AWTException e) {

e.printStackTrace();

}

return bfImage;

}

如果需要把截图保持为文件,使用ImageIO.write(RenderedImage im, String formatName, File output) ,示例代码:

/**

* 指定屏幕区域截图,保存到指定目录

* @param x

* @param y

* @param width

* @param height

* @param savePath - 文件保存路径

* @param fileName - 文件保存名称

* @param format - 文件格式

*/

public void screenShotAsFile(int x, int y, int width, int height, String savePath, String fileName, String format) {

try {

Robot robot = new Robot();

BufferedImage bfImage = robot.createScreenCapture(new Rectangle(x, y, width, height));

File path = new File(savePath);

File file = new File(path, fileName+ "." + format);

ImageIO.write(bfImage, format, file);

} catch (AWTException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

捕捉屏幕截图后,也许,我们需要对其剪裁。主要涉及两个类CropImageFilter和FilteredImageSource,关于这两个类的介绍,看java文档把。

/**

* BufferedImage图片剪裁

* @param srcBfImg - 被剪裁的BufferedImage

* @param x - 左上角剪裁点X坐标

* @param y - 左上角剪裁点Y坐标

* @param width - 剪裁出的图片的宽度

* @param height - 剪裁出的图片的高度

* @return 剪裁得到的BufferedImage

*/

public BufferedImage cutBufferedImage(BufferedImage srcBfImg, int x, int y, int width, int height) {

BufferedImage cutedImage = null;

CropImageFilter cropFilter = new CropImageFilter(x, y, width, height);

Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(srcBfImg.getSource(), cropFilter));

cutedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics g = cutedImage.getGraphics();

g.drawImage(img, 0, 0, null);

g.dispose();

return cutedImage;

}

如果剪裁后需要保存剪裁得到的文件,使用ImageIO.write,参考上面把截图保持为文件的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值