如何摆脱机器人拍摄的图像的黑色背景?

时间:2011-05-25 14:34:55

标签: java awtrobot

在按钮单击中我实现了代码,当我第一次单击按钮时它将获得x,y位置值,当我第二次单击按钮时它将获得x1,y1值并捕获图像。但不知何故,它还在原始图片中添加了黑色背景。我怎么能避免这个?

Toolkit tool = Toolkit.getDefaultToolkit();
c++;
Dimension d = tool.getScreenSize();
if(c==1)
{
    x = MouseInfo.getPointerInfo().getLocation().x; 
    y = MouseInfo.getPointerInfo().getLocation().y;
}
if(c==2)
{
    int x1= MouseInfo.getPointerInfo().getLocation().x; 
    int y1= MouseInfo.getPointerInfo().getLocation().y;
    Rectangle rect = new Rectangle(x,y,x1,y1);
    Robot robot = new Robot();
    String J="Screen";
    J=J+""+i;
    //*************
    String ext = ".jpg";
    String path = loc+J+ ext;
    File f = new File(path);
    i++;
    Thread t1 = new Thread();
    t1.sleep(100);
    BufferedImage img = robot.createScreenCapture(rect);
    // img.createGraphics();
    ImageIO.write(img,"jpeg",f);
    tool.beep();
    c=0;
    x=0;
    y=0;
    x1=0;
    y1=0;  
}

2 个答案:

答案 0 :(得分:0)

如果这是mouseClicked(MouseEvent event)方法(在MouseListener中),为什么使用:

MouseInfo.getPointerInfo().getLocation().x;

您可能应该使用MouseEvent上的方法:

event.getX();

event.getXOnScreen();

也许MouseInfo方法给你的值不正确。

答案 1 :(得分:0)

我想我发现了这个问题。 Rectangle的构造函数采用xy起始位置,以及heightwidth。看起来你给它2 x / y点。

请改为尝试:

int height = Math.max(y - y1, y1 - y);
int width = Math.max(x - x1, x1 - x);
Rectangle rect = new Rectangle(x,y,width, height);
相关问题