Tuesday, January 15, 2008

Java screenshot

This is a simple class that takes a screenshot and saves the image as a jpeg file.


screenshot.java :

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class screenshot {
int k;
public screenshot(){
k=0;
}
public void takeScreenShot() {

try {

Robot robot = new Robot();
BufferedImage bi=robot.createScreenCapture(new Rectangle(1024,768));
ImageIO.write(bi, "jpg", new File("E:\\PROJECTS\\Java Stuff\\My new Projects\\film\\imageTest"+k+".jpg"));
k++;
} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

In the other class you first create an instance of the screenshot class like this :
screenshot x=new screenshot();

Then we call the function:
x.takeScreenshot();

and a picture is saved into the folder defined earlier.



This is the code of the recording.java class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class recording implements Runnable {
screenshot x=new screenshot();
Thread th;
public static void main(String args[])
{
new recording();
}
public recording()
{
th=null;
start();
}

public void start()
{
if (th==null)
{
th=new Thread(this);
th.start();
}
}

public void run()
{
while(th!=null)
{
x.takeScreenShot();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}

public void stop()
{
}
}

This small java application takes a screenshot every second and saves it in your computer.If you want to capture all the action that takes place on your screen you can lower the 1000 miliseconds timeout.That will generate lots of images though :D
You can use this trick in many ways.You can spy on someone that chats on your pc ;), you can take screenshots of you playing some game and I will just let you think about others ... Hope you will find this useful !

No comments: