在RFT中,如何截取屏幕图像并保存到文件中?下面的脚本实现了3种类型的图像截取,包括截取整个屏幕的图像、截取指定区域的图像、截取某个测试对象的图像:
public void testMain(Object[] args)
{
// TODO 在此插入代码
captureScreen("C://temp1.jpg");
captureScreen("C://temp2.jpg",100,100,100,100);
startApp("calc");
计算器window().waitForExistence();
计算器window().activate();
captureScreen("C://temp3.jpg",(TestObject)计算器window());
}
截取整个屏幕的图像:
public static void captureScreen(String filename)
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width;
int height = screenSize.height;
doScreenCapture(filename, 0, 0, width, height);
}
截取指定的区域图像:
public static void captureScreen(String filename, int x, int y, int width, int height)
{
doScreenCapture (filename, x, y, width, height);
}
截取指定测试对象的图像:
public static void captureScreen(String filename, TestObject to)
{
Rectangle r = null;
//html
if (to.getProperties().containsKey(".bounds"))
r = (Rectangle)to.getProperty(".bounds");
//win
else if (to.getProperties().containsKey(".screenRectangle"))
r = (Rectangle)to.getProperty(".screenRectangle");
//swing
else if (to.getProperties().containsKey("bounds"))
{
r = (Rectangle)to.getProperty("bounds");
java.awt.Point point = null;
if (to.getProperties().containsKey("location")) //swt
point = (Point)to.getProperty("location");
else
point = (Point)to.getProperty("locationOnScreen");
if (point != null)
r.setLocation(point);
}
else
{
System.out.println("Error in captureScreen: could not capture test object");
return;
}
doScreenCapture(filename, r.x, r.y, r.width, r.height);
}
protected static void doScreenCapture (String filename, int x, int y, int width, int height)
{
try {
BufferedImage capture = null;
Rectangle area = new Rectangle(x, y, width, height);
Robot robot = new Robot();
capture = robot.createScreenCapture(area);
FileOutputStream out =
new FileOutputStream(filename);
JPEGImageEncoder encoder =
JPEGCodec.createJPEGEncoder(out);
encoder.encode(capture);
out.flush();
out.close();
}
catch (Exception e) {
System.out.println("Error in BitmapOps#doScreen: error capturing image: " + e);
}
}
}