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

问题描述

| 在“按钮单击”中,我已经实现了代码,当我第一次单击按钮时,它将获得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;  
}
    

解决方法

如果这是在
mouseClicked(MouseEvent event)
方法中(在
MouseListener
中),那么为什么要使用:
MouseInfo.getPointerInfo().getLocation().x;
您可能应该在
MouseEvent
上使用方法:
event.getX();
要么
event.getXOnScreen();
也许
MouseInfo
方法给您不正确的值。     ,我想我找到了问题。
Rectangle
的构造函数采用
x
y
起始位置,以及
height
width
。您好像给了它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);