Send a screenshot through an OutputStream
June 16, 2009 Leave a comment
Maybe have You ever tried to take a screenshot of Your screen in Java, and send it through an OutputStream (for example a Socket).
So we’re going to see how to do that in a simple way.
First of all, You have to take a screenshot of Your screen. That is as easy to do as writing in the console 🙂 We will use the class Robot. So, start by creating an instance of this class :
Robot myRobot = new Robot();
The Robot class contains a method named createScreenCapture() which take a Rectangle in parameter. This Rectangle corresponds to the area You want to take a screenshot. So typically, we’ll take the complete screen resolution. So let’s do that 🙂
int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; // get the height of the screen
int screnWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
// get the width of the screen Rectangle
myRect = new Rectangle(screenWidth, screenHeight);
// Take the screenshot
BufferedImage screenShot = myRobot.createScreenCapture(myRect);
Now we’ve got the screenshot, we have to send it through an OutputStream. There is several ways to do it. First, the simpliest of them, should be (You think) to use an ObjectOutputStream and pass the BufferedImage in parameter. But that doesn’t work !!
So to use an ObjectOutputStream, a solution consists in retrieving the byte array of the ImageBuffer. To do that, look at thi
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Now “fill” baos
ImageIO.write(screenShot, “jpg”, baos); // Here we want a JPEG file
Ok well. Now our baos is ok. We just have to call the method toByteArray() on our baos to retrieve a byte array 🙂 And this array can be send through an OutputStream 🙂
That’s it 🙂
Enjoy doing Java 🙂