您的位置:首页 > 编程语言 > Java开发

Java实现屏幕截图及剪裁

2014-09-14 09:22 856 查看

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,参考上面把截图保持为文件的代码。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 屏幕截图 剪裁