目录
adb截屏的另一种方式

Windows环境下,使用adb(Android debug bridge)来获取Android系统截图的通常办法是:
发送截图指令并保存,上传图片,(删除缓存)
代码为:

1
adb shell /system/bin/screencap -p /sdcard/temp.png
2
adb pull /sdcard/temp.png temp.png
3
adb shell rm /sdcard/temp.png

这种方式非常简单易懂,但是在需要频繁截取图片的情况是会占用较多的系统资源,也会频繁地读写磁盘,虽然不是不能用,但是用起来实在是不舒服。


所以在几番查找之后,找到了另一种方法:
adb shell中的screencap指令描述如下:

1
screencap -h
2
usage: screencap [-hp] [-d display-id] [FILENAME]
3
   -h: this message
4
   -p: save the file as a png.
5
   -d: specify the display id to capture, default 0.
6
If FILENAME ends with .png it will be saved as a png.
7
If FILENAME is not given, the results will be printed to stdout.

在不给出文件名的时候会在stdout中输出文件,大体看就是一堆乱码了,但是可以直接使用管道符保存到电脑中,省去了保存在手机中的步骤,并且速度会更快,资源占用也会少很多

1
adb shell screencap -p > temp.png

在Windows环境下,这种方式保存的图片会无法读取,原因是文件中的”\n”被替换成了”\r\n”,导致了图片的编码错误,所以需要将其替换回去

1
def screencap(filename="temp.png"):
2
    sp = subprocess.Popen("adb exec-out screencap -p", stdout=subprocess.PIPE)
3
    pic = sp.stdout.read().replace(b'\r\n', b'\n')
4
    sp.kill()
5
    with open("{}".format(filename), "wb") as f:
6
        f.write(pic)

具体步骤就是将stdout储存到变量,然后替换再保存,之后图片便可以正常读取了


注意事项:
Android Debug Bridge version 1.0.32
之前有尝试过,在更高版本的adb中上述方法无效,还需要进一步研究

相关链接:
https://stackoverflow.com/questions/13578416/read-binary-stdout-data-from-adb-shell

文章作者: Stort Inter
文章链接: https://stortinter.github.io/2019/12/01/adb%E6%88%AA%E5%B1%8F%E7%9A%84%E5%8F%A6%E4%B8%80%E7%A7%8D%E6%96%B9%E5%BC%8F/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Cold Dream

评论