前言
查看了相關文章然後一筆一筆打代碼再調試成功出結果,
eguid的博客
不保證代碼能夠原封不動就能運行,
這裏做一下記錄。
ps:代碼內容有改動,原版的可以看原作者的。
代碼
package net.w2p.JCVStudio.zhiboStudy;
import org.bytedeco.javacv.CanvasFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
/***
* https://blog.csdn.net/eguid_1/article/details/64922443
* java原生實現屏幕設備遍歷和屏幕採集(捕獲)等功能
* **/
public class Lesson07 {
Logger logger= LoggerFactory.getLogger("Lesson07");
public void captureScreen(){
//--獲取屏幕大小
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
//指定捕獲的屏幕區域大小。這裏使用全屏捕獲。
Rectangle rectangle=new Rectangle(screenSize);
//--獲取本地環境
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs=ge.getScreenDevices();
logger.info("找到了{}個屏幕設備。",gs.length);
Robot robot=null;
int ret=-1;
for(int index=0;index<10;index++){
GraphicsDevice g=gs[index];
try{
robot=new Robot(g);
BufferedImage img=robot.createScreenCapture(rectangle);
if(img!=null&&img.getWidth()>1){
ret=index;
break;
}
}
catch (Exception ed){
ed.printStackTrace();
logger.info("打開第{}個屏幕設備時候失敗,嘗試打開第{}個的",index,index+1);
}
}
if(ret==-1){
logger.info("抱歉,找不到可用屏幕設備。");
return;
}
logger.info("可用屏幕設備序號爲:{}",ret);
CanvasFrame frame=new CanvasFrame("屏幕錄製測試");
int width=800,height=600;
frame.setBounds((int)(screenSize.getWidth()-width)/2,(int)(screenSize.getHeight()-height)/2
,width,height
);
frame.setCanvasSize(width,height);
while (frame.isShowing()){
// 從當前屏幕中讀取的像素圖像,該圖像不包括鼠標光標
logger.info("開始錄製");
BufferedImage image=robot.createScreenCapture(rectangle);
frame.showImage(image);
try{
Thread.sleep(45);
}
catch (Exception ed){
ed.printStackTrace();
}
}
frame.dispose();
}
public static void main(String[] args) throws Exception{
Lesson07 test=new Lesson07();
test.captureScreen();
}
}