用Java Robot实现屏幕截取、远程监控

来源:互联网 发布:金鼎网络微营销软件 编辑:程序博客网 时间:2024/06/06 05:02
远程监控或远程教学,常常需要对计算机的屏幕进行截取,由于屏幕截取是比较接近操作系统的操作。Java JDK1.4 的Robot对象可以完成对"屏幕"像素的拷贝,完成屏幕图像截取操作。Java应用程序中可以直接调用此对象,完成对特定应用程序的屏幕截取,如果将此功能配合网络,便可以轻而易举地实现远程服务器屏幕的监视。 

   在Java JDK1.4 中提供的"机器人"Robot类用于产生与本地操作系统有关的底层输入、测试应用程序运行或自动控制应用程序运行。Robot类提供了一个方法:createScreenCapture(..),可以直接将全屏幕或某个屏幕区域的像素拷贝到一个BufferedImage对象中,我们只需要将该对象写入到一个图像文件之中,就完成了屏幕到图像的拷贝过程。示例如下: 
import java.awt.Dimension; 
import java.awt.Rectangle; 
import java.awt.Robot; 
import java.awt.Toolkit; 
import java.awt.image.BufferedImage; 
import java.io.File; 

import javax.imageio.ImageIO; 

public class ScreenCaptureUtil { 

    private String fileName; //文件的前缀 
    
private String defaultName = "GuiCamera"; 

static int serialNum = 0; 

private String imageFormat; //图像文件的格式 

private String defaultImageFormat="png"; 

Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); 

/**************************************************************** 
   * 默认的文件前缀为GuiCamera,文件格式为PNG格式 
   * The default construct will use the default 
   * Image file surname "GuiCamera", 
   * and default image format "png" 
****************************************************************/ 
public ScreenCaptureUtil() { 
    fileName = defaultName; 
    imageFormat = defaultImageFormat; 
    } 
  
/**************************************************************** 
   * @param s the surname of the snapshot file 
   * @param format the format of the  image file, 
   * it can be "jpg" or "png" 
   * 本构造支持JPG和PNG文件的存储 
****************************************************************/ 
public ScreenCaptureUtil(String s,String format) { 
    fileName = s; 
    imageFormat = format; 


/**************************************************************** 
   * 对屏幕进行拍照 
   * snapShot the Gui once 
****************************************************************/ 
public void snapShot() 

    try 
    { 
        //拷贝屏幕到一个BufferedImage对象screenshot 
        BufferedImage screenshot = (new Robot()).createScreenCapture(new 
            Rectangle(0, 0, (int) d.getWidth(), (int) d.getHeight())); 
        serialNum++; 
        //根据文件前缀变量和文件格式变量,自动生成文件名 
        String name = fileName + String.valueOf(serialNum) + "." + imageFormat; 
        File f = new File(name); 
        System.out.print("Save File " + name); 
        //将screenshot对象写入图像文件 
        ImageIO.write(screenshot, imageFormat, f); 
        System.out.print("..Finished!\n"); 
    } 
    catch (Exception ex) { 
      System.out.println(ex); 
    } 


public static void main(String[] a) 

ScreenCaptureUtil ScreenCapture = new ScreenCaptureUtil("d:\\Hello", "jpg"); 
ScreenCapture.snapShot(); 



   上述代码旨在"抛砖引玉",如果将此ScreenCaptureUtil增加多线程和网络功能,可以实现远程监控网络上另一台计算机屏幕。



原文地址:http://dead-knight.iteye.com/blog/289052

1 0
原创粉丝点击