uiautomator是android自动化测试工具。
在工作中遇到需要将头像获取出来,涉及到使用uiautomator得到我们要截取图像的坐标,根据坐标将图像截取出并保存为bitmap。需要注意的是 在截图和使用bitmap对截图进行操作时 会出现内存溢出OOM的错误,需要在android的AndroidManifest.xml中添加
android:largeHeap="true"
也就是说给手机分配更大的堆
public static void cutImage(Rect rect, String filePath) { BitmapFactory.Options bfOptions = new BitmapFactory.Options(); bfOptions.inDither = false; bfOptions.inTempStorage = new byte[12 * 1024]; bfOptions.inJustDecodeBounds = true; Bitmap m = BitmapFactory.decodeFile(filePath); m = m.createBitmap(m, rect.left, rect.top, rect.width(), rect.height());//获取头像 ByteArrayOutputStream bos = new ByteArrayOutputStream(); m.compress(Bitmap.CompressFormat.JPEG, 90, bos);//压缩图片 byte[] data = bos.toByteArray();//转换成字节 String img=new String(Base64.encodeToString(data,Base64.DEFAULT));//base64编码 //保存图片到sdcard saveImage(m, "cutImage"); } public static void saveImage(Bitmap bitmap, String name) { FileOutputStream out = null; try { out = new FileOutputStream("/storage/emulated/0/Pictures/" + name + ".jpg"); if (out != null) { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void getImage(UiDevice device,String objectResourceId) { UiObject uiObject = CommonUtils.findByResourceId(objectResourceId, device); try { Rect rect = uiObject.getBounds(); String path = "/storage/emulated/0/Pictures/screenshot.png"; File file = new File(path); device.takeScreenshot(file); cutImage(rect, path); } catch (Exception e) { e.printStackTrace(); } }