4

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user1638875
  • 105
  • 3
  • 10

1 Answers1

8

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());
obataku
  • 29,212
  • 3
  • 44
  • 57
  • 1
    *"I'd really have to ask.."* Good question. Apparently the OP presumes we all sit around, obsessing on their questions alone. A previous question explained that `createScreenCapture` produces a black image for some full-screen apps. Also a good answer. +1 – Andrew Thompson Sep 04 '12 at 01:55
  • First of all, thank you for your anser. Secondy, I don't really know why but when I run your code I receive the following error: "SEVERE: null java.lang.NullPointerException" – user1638875 Sep 04 '12 at 08:43
  • I think it comes from my following code : "ImageIO.write(copy,"png", file1); ", is that right ? – user1638875 Sep 04 '12 at 08:59
  • @user1638875 I don't know, I didn't write that code. The name of the exception is not enough information for me to help... perhaps if you had a full trace. – obataku Sep 06 '12 at 00:06