Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate Print Screen under Windows

I know we can simulate the print screen with the following code:

 robot.keyPress(KeyEvent.VK_PRINTSCREEN);

..but then how to return some BufferedImage?

I found on Google some method called getClipboard() but Netbeans return me some error on this one (cannot find symbol).

I am sorry to ask this, but could someone show me a working code on how returning from this key press a BufferedImage that I could then save?

like image 750
user1638875 Avatar asked Feb 20 '23 07:02

user1638875


1 Answers

This won't necessarily give you a BufferedImage, but it will be an Image. This utilizes Toolkit.getSystemClipboard.

final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor)) {
  final Image screenshot = (Image) clipboard.getData(DataFlavor.imageFlavor);
  ...
}

If you really need a BufferedImage, try as follows...

final GraphicsConfiguration config
    = GraphicsEnvironment.getLocalGraphicsEnvironment()
          .getDefaultScreenDevice().getDefaultConfiguration();
final BufferedImage copy = config.createCompatibleImage(
    screenshot.getWidth(null), screenshot.getHeight(null));
final Object monitor = new Object();
final ImageObserver observer = new ImageObserver() {

  public void imageUpdate(final Image img, final int flags,
      final int x, final int y, final int width, final int height) {
    if ((flags & ALLBITS) == ALLBITS) {
      synchronized (monitor) {
        monitor.notifyAll();
      }
    }
  }
};
if (!copy.getGraphics().drawImage(screenshot, 0, 0, observer)) {
  synchronized (monitor) {
    try {
      monitor.wait();
    } catch (final InterruptedException ex) { }
  }
}

Though, I'd really have to ask why you don't just use Robot.createScreenCapture.

final Robot robot = new Robot();
final GraphicsConfiguration config
    = GraphicsEnvironment.getLocalGraphicsEnvironment()
          .getDefaultScreenDevice().getDefaultConfiguration();
final BufferedImage screenshot = robot.createScreenCapture(config.getBounds());
like image 125
obataku Avatar answered Feb 27 '23 19:02

obataku