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 intscrenWidth = 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