当我在我的Macbook上使用py adb exec-out screencap -p
或commands.getstatusoutput
中的subprocess.call
获取截图时,我可以获得完美的png文件字节,但在Windows上运行时,我只是得到当Image.open()
cannot identify image file <_io.BytesIO object at 0x000002ADDDB49BF8>
def cmd(line, out_is_binary=False):
cmdline = line if isinstance(line, str) else ' '.join(line)
with tempfile.TemporaryFile() as stdout:
status = subprocess.call(line, stdout=stdout, stderr=stdout)
stdout.seek(0)
output = stdout.read()
output = str(output, 'utf-8') if not out_is_binary else output
output_log = output if not out_is_binary else '<binary data>'
print('"%s" returned %s, and says:%s%s' % (cmdline, status, os.linesep, output_log))
return status, output
def capture():
line = [ADB_BIN, 'exec-out', 'screencap', '-p']
status, output = cmd(line, out_is_binary=True)
if status:
raise RuntimeError('通过USB调试截屏失败')
fp = BytesIO(output)
return Image.open(fp)
PS:这个问题不应该是adb问题的重复。因为这是在Windows中使用DAMMIT Windows CMD或Python获取屏幕截图的方法。
答案 0 :(得分:0)
最后我得到了像bellow一样的解决方案,如果在windows上运行,使用base64传输数据然后在python中解码
def capture():
line = [ADB_BIN, 'exec-out', 'screencap', '-p']
if os.name == 'nt':
line = [ADB_BIN, 'shell', 'screencap -p | base64']
status, output = cmd(line, out_is_binary=True)
if status:
raise RuntimeError('通过USB调试截屏失败')
if os.name == 'nt':
output = base64.decodebytes(output)
fp = BytesIO(output)
return Image.open(fp)