Monday, May 20, 2013

Screen capture


The ScreenCapture is a program that enables you to capture your computer on screen activities. The captured images of the screen are stored in a folder called tempDir. It is easy to capture your screen with ScreenCapture. When the program opens you can click the Start Capture to begin the screen capture task. When you want to stop the capturing task, click Stop Capture.

Screen Capture in Java


ScreenCapture source code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;

class ScreenCapture extends JFrame implements ActionListener{
  JButton btCap;
Robot rb;
boolean capturing=true;
CaptureControl cc;
ScreenCapture() throws AWTException{

setTitle("Screen Capture");
setIconImage(getToolkit().getImage("icon.png"));
setPreferredSize(new Dimension(300,60));

btCap=new JButton("Start Capture");
btCap.addActionListener(this);
add(btCap,BorderLayout.CENTER);

setResizable(false);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
rb=new Robot(); //create Robot object used in capture

}


public void actionPerformed(ActionEvent e){
try{
if(btCap.getText().equals("Start Capture")){ //start capturing the screen
btCap.setText("Stop Capture");
setState(ICONIFIED);
cc=new CaptureControl();
cc.start();
}
else if(btCap.getText().equals("Stop Capture")){ //stop capturing the screen
cc.stopCapture();
btCap.setText("Stop Capture");

}

}catch(Exception ee){}



}



class CaptureControl extends Thread{
boolean started;
File tempDir;
Dimension ds;
CaptureControl (){
started=true;
tempDir=new File("tempDir");
if(!tempDir.exists())
1 tempDir.mkdir();
2 ds=getToolkit().getScreenSize();
}

public void run(){
try{
while(started){
3 BufferedImage bi=rb.createScreenCapture(new Rectangle(ds));
4 ImageIO.write(bi,"jpg",new File(tempDir.getAbsolutePath()+"/"+System.currentTimeMillis()+".jpg"));
5 Thread.sleep(100);
}

}catch(Exception ie){}
}


public void stopCapture(){
started=false;

}


}



public static void main(String args[])  throws Exception{
   
new ScreenCapture();
 
               }


}


Code Explanation
1 Create the tempDir folder to store the captured images.
2 Get the dimension of the screen so you are able to capture the full screen.
3 Capture the screen by using the createScreenCapture of the Robot rb object. The result of each capture is a BufferedImage object.
4 Write the BufferedImage object bi to a file.
5 The interval or time delay between each capture action is 100 milliseconds. The program continues to capture the screen while there is no interruption. To interrupt or stop the capturing task, you will click Stop Capture.

No comments:

Post a Comment