同样发现,UIAutomator 提供默认截图方法 生成图片文件也是非常大,压缩算法并没生效。导致截图链路上整体耗时会造成每次截图在平均 2-5s 左右,影响到了自动化整体时间。 考虑到单独引进一套压缩算法较重,且可能后续无资源维护,所以决定研究安卓源码,试图从根本解决压缩无效的问题。
/**
- Write a compressed version of the bitmap to the specified outputstream.
- If this returns true, the bitmap can be reconstructed by passing a
- corresponding inputstream to BitmapFactory.decodeStream(). Note: not
- all Formats support all bitmap configs directly, so it is possible that
- the returned bitmap from BitmapFactory could be in a different bitdepth,
- and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque
- pixels).
- @param format The format of the compressed image
- @param quality Hint to the compressor, 0-100. 0 meaning compress for
-
small size, 100 meaning compress for max quality. Some
-
formats, like PNG which is lossless, will ignore the
-
quality setting
- @param stream The outputstream to write the compressed data.
- @return true if successfully compressed to the specified stream.
*/
public boolean compress(CompressFormat format, int quality, OutputStream stream) {
…
}
public boolean takeScreenshot(File storePath, int quality) {
Bitmap screenshot = mUiAutomation.takeScreenshot();
…
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storePath));
screenshot.compress(Bitmap.CompressFormat.PNG, quality, bos);
}
…
return true;
}
根据以上安卓源码,跟踪到系统压缩方法。看注释,似乎发现了问题所在,看 takeScreenshot
方法, 调用了 Bitmap 的 Compress 压缩方法,传的参数写死了 Bitmap.CompressFormat.PNG,
格式,根据注释说明,Compress 方法又对 png 格式图片的压缩忽略的,所以导致获取到的图片都很大。马上重写系统方法,直接调用压缩方法,传入 JPEG 去验证可行性,马上得出了解决方案。