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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With