gpt4 book ai didi

java - ScreenCap 直接 toByteArray ,跳过保存到内存

转载 作者:行者123 更新时间:2023-12-02 01:59:40 32 4
gpt4 key购买 nike

我正在尝试优化下面的代码,是否可以直接将 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);

最佳答案

Screencap usage :

"usage: %s [-hp] [-d display-id] [FILENAME]\n"
" -h: this message\n"
" -p: save the file as a png.\n"
" -d: specify the display id to capture, default %d.\n"
"If FILENAME ends with .png it will be saved as a png.\n"
"If FILENAME is not given, the results will be printed to 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();
}

关于java - ScreenCap 直接 toByteArray ,跳过保存到内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51782364/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com