两种方法:
- 普通api截屏
只能截取当前软件的视图范围, 如果有分屏操作, 就不好 - 系统命令截屏
即使分屏, 也可以截取整屏
普通截屏:
// 截屏
public static Bitmap screenshotView(View view) {
// view.setDrawingCacheEnabled(true); // 设置缓存,可用于实时截图
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
// view.setDrawingCacheEnabled(false); // 清空缓存,可用于实时截图
return bitmap;
}
// 位图转 Byte
private static byte[] getBitmapByte(Bitmap bitmap){
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 参数1转换类型,参数2压缩质量,参数3字节流资源
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return out.toByteArray();
}
/*
存本地
*/
public static void save(Context context, String filePath, String fileName, Bitmap bmp) {
if (bmp == null) return;
// 首先保存图片
File appDir = new File(filePath);
if (!appDir.exists()) {
appDir.mkdir();
}
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 把文件插入到系统图库
// try {
// MediaStore.Images.Media.insertImage(context.getContentResolver(),
// file.getAbsolutePath(), fileName, null);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
// // 最后通知图库更新
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
}
系统命令截屏
// 调用
GpioUtil.exeCommand("screencap /sdcard/`date +%Y-%m-%d`.png", true)
/*
* 系统截屏命令
*
* */
public static void exeCommand(String cmd, boolean isRoot) {
if (TextUtils.isEmpty(cmd)) {
return null;
}
//StringBuilder result = new StringBuilder();
DataOutputStream dos = null;
DataInputStream dis = null;
Process p = null;
try {
if (isRoot) {
p = Runtime.getRuntime().exec("su");
} else {
p = Runtime.getRuntime().exec("sh");
}
dos = new DataOutputStream(p.getOutputStream());
dis = new DataInputStream(p.getInputStream());
dos.writeBytes(cmd + "\n");
dos.flush();
dos.writeBytes("exit\n");
dos.flush();
// String line = null;
// while ((line = dis.readLine()) != null) {
// Log.d(TAG,"line="+line);
// result.append(line);
// }
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//return result.toString();
}
网友评论