Java : BufferedImage to Bitmap format

Anand S Kumar picture Anand S Kumar · Jun 13, 2011 · Viewed 12.1k times · Source

I have a program in which i capture the screen using the code :

robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

Now i want to convert this BufferedImage into Bitmap format and return it through a function for some other need, Not save it in a file. Any help please??

Answer

aioobe picture aioobe · Jun 13, 2011

You need to have a look at ImageIO.write.

If you want the result in the form of a byte[] array, you should use a ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(yourImage, "bmp", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();