我正在尝试优化下面的代码,是否可以将ScreenCap直接复制到字节数组,所以我可以跳过将其保存到内存的步骤。
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/colorPickerTemp.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
InputStream inputStream = new FileInputStream("/sdcard/colorPickerTemp.png");//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[1000000];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
final String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
答案 0 :(得分:2)
“用法:%s [-hp] [-d display-id] [FILENAME] \ n”
“ -h:此消息\ n”
“ -p:将文件另存为png。\ n”
“ -d:指定要捕获的显示ID,默认为%d。\ n”
“如果FILENAME以.png结尾,它将另存为png。\ n”
“如果未提供FILENAME,结果将被打印到stdout。\ n”
因此您可以执行以下操作:
public String getScreenshotBase64() throws IOException {
return Base64.encodeToString(getScreenshotImageBytes(), Base64.NO_WRAP);
}
public byte[] getScreenshotImageBytes() throws IOException {
Process process = Runtime.getRuntime().exec("su");
OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream());
outputStream.write("/system/bin/screencap -p\n");
outputStream.flush();
byte[] bytes = readBytes(process.getInputStream());
outputStream.write("exit\n");
outputStream.flush();
outputStream.close();
return bytes;
}
public byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}