This function handle the screenshot - Java Swing

Java examples for Swing:Screen

Description

This function handle the screenshot

Demo Code


//package com.java2s;
import java.awt.AWTException;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;

import java.io.IOException;

import javax.imageio.ImageIO;

public class Main {
    /**/*from w ww  . ja v a 2  s .  c om*/
     * This function handle the screenshot
     * @param {@link Boolean} showCursor if the cursor in the screenshot need to be shown
     * @return byte[] that contain the screenshot (jpeg)
     */
    public static byte[] takeScreenShot(boolean showCursor) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedImage img = null;
        byte[] out = null;

        try {
            img = new Robot().createScreenCapture(new Rectangle(Toolkit
                    .getDefaultToolkit().getScreenSize()));

            if (showCursor) {
                Image cursor = ImageIO.read(new File(
                        "res/ratty/img/cursor.gif"));
                int x = MouseInfo.getPointerInfo().getLocation().x;
                int y = MouseInfo.getPointerInfo().getLocation().y;

                Graphics2D graphics2D = img.createGraphics();
                graphics2D.drawImage(cursor, x, y, 16, 16, null);
            }
            //TODO: Add multiple images compressions
            ImageIO.write(img, "jpg", baos);
            baos.flush();
            out = baos.toByteArray();
            baos.close();
        } catch (HeadlessException | AWTException | IOException e) {
            e.printStackTrace();
        }

        return out;
    }
}

Related Tutorials