0

When I use adb exec-out screencap -p in python commands.getstatusoutput or subprocess.call on my Macbook to get screenshot like bellow, I can get perfect png file bytes, but when running on Windows, I just get an cannot identify image file <_io.BytesIO object at 0x000002ADDDB49BF8> when Image.open()

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: This question should not be the duplication of adb question. Because the point in this is the way to get a screenshot in a DAMMIT Windows CMD or Python in Windows.

Ian Hu
  • 295
  • 3
  • 7

1 Answers1

1

finally I got the solution like bellow, if run on windows, use base64 to transfer data and then decode it in 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)
Ian Hu
  • 295
  • 3
  • 7