zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java实现屏幕截图及剪裁

JAVA 实现 屏幕 截图 剪裁
2023-06-13 09:15:45 时间

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

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

newRectangle(intx,inty,intwidth,intheight),四个参数分别是矩形左上角x坐标,矩形左上角y坐标,矩形宽度,矩形高度。截图方法返回BufferedImage对象,示例代码:

/**
*指定屏幕区域截图,返回截图的BufferedImage对象
*@paramx
*@paramy
*@paramwidth
*@paramheight
*@return
*/
publicBufferedImagegetScreenShot(intx,inty,intwidth,intheight){
BufferedImagebfImage=null;
try{
Robotrobot=newRobot();
bfImage=robot.createScreenCapture(newRectangle(x,y,width,height));
}catch(AWTExceptione){
e.printStackTrace();
}
returnbfImage;
}

 如果需要把截图保持为文件,使用ImageIO.write(RenderedImageim,StringformatName,Fileoutput),示例代码:

/**
*指定屏幕区域截图,保存到指定目录
*@paramx
*@paramy
*@paramwidth
*@paramheight
*@paramsavePath-文件保存路径
*@paramfileName-文件保存名称
*@paramformat-文件格式
*/
publicvoidscreenShotAsFile(intx,inty,intwidth,intheight,StringsavePath,StringfileName,Stringformat){
try{
Robotrobot=newRobot();
BufferedImagebfImage=robot.createScreenCapture(newRectangle(x,y,width,height));
Filepath=newFile(savePath);
Filefile=newFile(path,fileName+"."+format);
ImageIO.write(bfImage,format,file);
}catch(AWTExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}

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

/**
*BufferedImage图片剪裁
*@paramsrcBfImg-被剪裁的BufferedImage
*@paramx-左上角剪裁点X坐标
*@paramy-左上角剪裁点Y坐标
*@paramwidth-剪裁出的图片的宽度
*@paramheight-剪裁出的图片的高度
*@return剪裁得到的BufferedImage
*/
publicBufferedImagecutBufferedImage(BufferedImagesrcBfImg,intx,inty,intwidth,intheight){
BufferedImagecutedImage=null;
CropImageFiltercropFilter=newCropImageFilter(x,y,width,height);
Imageimg=Toolkit.getDefaultToolkit().createImage(newFilteredImageSource(srcBfImg.getSource(),cropFilter));
cutedImage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphicsg=cutedImage.getGraphics();
g.drawImage(img,0,0,null);
g.dispose();
returncutedImage;
}

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