我想在我的MacOS中截取某些应用的截图,即使是在另一个虚拟屏幕上也不在活动屏幕上。
我可以使用以下代码进行活动屏幕捕获但是如何捕获给定的应用程序?
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
public class Screenshot {
public static void main(String args[]) throws AWTException, IOException {
while(true) {
String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
BufferedImage screencapture = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())
);
// Save as JPEG
File file = new File("./screens/screencapture" + timeStamp + ".jpg");
ImageIO.write(screencapture, "jpg", file);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:5)
尝试使用/ usr / sbin / screencapture,并使用
调用它Runtime.getRuntime().exec("/usr/sbin/screencapture");
以下是screencapture的使用输出
usage: screencapture [-icMPmwsWxSCUtoa] [files]
-c force screen capture to go to the clipboard
-C capture the cursor as well as the screen. only in non-interactive modes
-d display errors to the user graphically
-i capture screen interactively, by selection or window
control key - causes screen shot to go to clipboard
space key - toggle between mouse selection and
window selection modes
escape key - cancels interactive screen shot
-m only capture the main monitor, undefined if -i is set
-M screen capture output will go to a new Mail message
-o in window capture mode, do not capture the shadow of the window
-P screen capture output will open in Preview
-s only allow mouse selection mode
-S in window capture mode, capture the screen not the window
-t<format> image format to create, default is png (other options include pdf, jpg, tiff and other formats)
-T<seconds> Take the picture after a delay of <seconds>, default is 5
-w only allow window selection mode
-W start interaction in window selection mode
-x do not play sounds
-a do not include windows attached to selected windows
-r do not add dpi meta data to image
-l<windowid> capture this windowsid
-R<x,y,w,h> capture screen rect
files where to save the screen capture, 1 file per screen
我认为带窗口id的-w选项是要使用的选项。但要获得窗口ID,您可能需要另一个实用程序。一个这样的效用是pyscreencapture。 否则,我确信谷歌搜索如何获取窗口ID将导致更多方法来获取您需要的窗口ID。
虽然我不完全确定虚拟屏幕的含义,但您可能无法获取窗口ID或捕获屏幕。
答案 1 :(得分:3)
&#34;不幸的是&#34;你需要JNI在这里。基本上,您需要访问Cocoa的一些CoreGraphics
和ImageIO
API。算法如下:
CGWindowListCopyWindowInfo()
以获取有关系统中所有窗口的信息。ImageRef
CGWindowListCreateImage()
CGImageDestinationRef
函数将其保存到文件中。由于Java不能直接调用Cocoa函数,因此需要Java和Cocoa之间的桥梁,这是一个利用JNI允许Java代码到达ObjectiveC实现函数的桥梁。
你的问题提出了相当大的挑战,所以我开始了一个github(https://github.com/cristik/cocoa4java)的小项目,它提供了拍摄应用程序窗口快照所需的功能。我认为您可以在找到与进程关联的窗口以及检索这些窗口的快照方面找到您需要的所有内容。还有一个小示例类,它使用这些功能来帮助您开始使用库。