我是java的初学者,我正在尝试编写一个简单的屏幕捕获程序。我写了一个简单的SWING
桌面应用程序,其中包含一个按钮和一个文本字段,我想要做的是,当用户点击该按钮时,应用程序会使用awt.Robot
获取屏幕快照,并将该图像和文本发送到我服务器上的PHP脚本。
到目前为止我的快照功能是:
private void takeSnapShot(){
try {
Robot robot = new Robot();
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = robot.createScreenCapture(area);
//Try to save the captured image
try {
File file = new File("screenshot_full.png");
ImageIO.write(bufferedImage, "png", file);
} catch (IOException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (AWTException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
}
你可以看到它到目前为止相当简单,但我不知道如何将该图像发送到我的PHP脚本而不实际将图像存储在用户的PC上。
哦,我正在使用apache httpClient
库与Web服务器进行通信。对于文本,我想我可以在URL中将其作为获取查询传递,但我不知道如何处理图像。
答案 0 :(得分:2)
ImageIO.write
可以选择OutputStream
。
因此,如果您不想将图像写入File
,则可以将其写入不同的流而不是......
例如......
OutputStream os = null;
try {
Robot robot = new Robot();
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = robot.createScreenCapture(area);
//Try to save the captured image
try {
os = ...;
ImageIO.write(bufferedImage, "png", os);
} catch (IOException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
os.close();
} catch (Exception exp) {
}
}
} catch (AWTException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
当然,我不知道您在哪里发送数据,因此您需要自己定义OutputStream
。
如果你有内存,你可以写一个ByteArrayOutputStream
,然后把它写到你将来需要的任何输出流......
答案 1 :(得分:0)
为什么不将它变为WebsService并让PHP使用它?您可以使用某种Base64编码器通过WebsService发送二进制数据。
你可以这样做来获取BufferedImage的字节:
byte[] binaryData = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData();
答案 2 :(得分:0)
要略微修改现有方法,也许您可以使用临时文件,然后在完成后将其删除。也许它可能看起来像:
private void takeSnapShot(){
try {
Robot robot = new Robot();
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bufferedImage = robot.createScreenCapture(area);
//Try to save the captured image
try {
File file = File.createTempFile(Long.toString(System.currentTimeMillis()), ".png");
ImageIO.write(bufferedImage, "png", file);
//send image
file.delete();
} catch (IOException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (AWTException ex) {
Logger.getLogger(ScrCaptFrm.class.getName()).log(Level.SEVERE, null, ex);
}
}
另一个替代方法是从int[][]
构建一个BufferedImage
,它将保留图像每个像素的RGB值:
public int[][] getColors(final BufferedImage image){
assert image != null;
final int[][] colors = new int[image.getWidth()][image.getHeight()];
for(int x = 0; x < colors.length; x++)
for(int y = 0; y < colors[x].length; y++)
colors[x][x] = image.getRGB(x, y);
return colors;
}
我对你希望实现的目标有点不确定;你打算用图像做什么?