我知道我们可以用下面的代码模拟打印屏幕:
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
..但是如何返回一些BufferedImage
?
我在 Google 上找到了一些名为 getClipboard()
的方法,但 Netbeans 对此返回了一些错误(找不到符号)。
我很抱歉问这个问题,但是有人可以告诉我一个工作代码,说明如何从该键返回时按下一个我可以保存的 BufferedImage
吗?
最佳答案
这不一定会给你一个 BufferedImage
,但它会是一个 Image
。这利用了 Toolkit.getSystemClipboard
.
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
if (clipboard.isDataFlavorAvailable(DataFlavor.imageFlavor)) {
final Image screenshot = (Image) clipboard.getData(DataFlavor.imageFlavor);
...
}
如果您确实需要BufferedImage
,请尝试如下...
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) { }
}
}
不过,我真的不得不问你为什么不直接使用 Robot.createScreenCapture
.
final Robot robot = new Robot();
final GraphicsConfiguration config
= GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
final BufferedImage screenshot = robot.createScreenCapture(config.getBounds());
关于java - Windows下模拟打印屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12255441/