java实现截屏

来源:互联网 发布:华为mate9 知乎 编辑:程序博客网 时间:2024/05/16 01:57
 1 import java.awt.Dimension; 2 import java.awt.Rectangle; 3 import java.awt.Robot; 4 import java.awt.Toolkit; 5 import java.awt.image.BufferedImage; 6 import java.io.File; 7  8 import javax.imageio.ImageIO; 9 10 /*******************************************************************11 * 该JavaBean可以直接在其他Java应用程序中调用,实现屏幕的"拍照"12 * This JavaBean is used to snapshot the GUI in a13 * Java application! You can embeded14 * it in to your java application source code, and us15 * it to snapshot the right GUI of the application16 * @see javax.ImageIO17 * @author liluqun (liluqun@263.net)18 * @version 1.019 *20 *****************************************************/21 22 public class GuiCamera23 {  24     private String fileName; //文件的前缀25     private String defaultName = "GuiCamera";26     static int serialNum=0;27     private String imageFormat; //图像文件的格式28     private String defaultImageFormat="png";29     Dimension d = Toolkit.getDefaultToolkit().getScreenSize();30 31     /****************************************************************32      * 默认的文件前缀为GuiCamera,文件格式为PNG格式33      * The default construct will use the default34      * Image file surname "GuiCamera",35      * and default image format "png"36      ****************************************************************/37     public GuiCamera() {38       fileName = defaultName;39       imageFormat=defaultImageFormat;40    41     }42 43     /****************************************************************44      * @param s the surname of the snapshot file45      * @param format the format of the  image file,46      * it can be "jpg" or "png"47      * 本构造支持JPG和PNG文件的存储48      ****************************************************************/49     public GuiCamera(String s,String format) {50    51       fileName = s;52       imageFormat=format;53     }54    55     /****************************************************************56      * 对屏幕进行拍照57      * snapShot the Gui once58      ****************************************************************/59     public void snapShot() {60    61       try {62       //拷贝屏幕到一个BufferedImage对象screenshot63         BufferedImage screenshot = (new Robot()).createScreenCapture(new64             Rectangle(0, 0, (int) d.getWidth(), (int) d.getHeight()));65         serialNum++;66         //根据文件前缀变量和文件格式变量,自动生成文件名67         String name=fileName+String.valueOf(serialNum)+"."+imageFormat;68         File f = new File(name);69         System.out.print("Save File "+name);70       //将screenshot对象写入图像文件71         ImageIO.write(screenshot, imageFormat, f);72         System.out.print("..Finished!\n");73       }74       catch (Exception ex) {75         System.out.println(ex);76       }77     }78 79     public static void main(String[] args)80     {81         GuiCamera cam= new GuiCamera("d:\\Hello", "png");//82 83         cam.snapShot();84     }85 }

原文:http://bbs.chinaunix.net/thread-770968-1-4.html

0 0
原创粉丝点击