Send a screenshot through an OutputStream

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 πŸ™‚


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: