adb exec-out/binary transfer directly to host instead of tty/pty mangle

本文深入探讨了ADB exec-out命令的使用技巧,对比adb shell,该命令不使用pty,适用于处理二进制输出,如通过screencap捕获屏幕截图。同时,文章提供了在压缩目录时如何避免STDERR干扰的解决方案。

Unlike adb shell the adb exec-out command doesn't use pty which mangles the binary output. So you can do

Linux$ adb exec-out screencap -p > test.png    (Note: Linux  \n will be converted into \r\n on Windows) 
https://android.googlesource.com/platform/system/core/+/5d9d434efadf1c535c7fea634d5306e18c68ef1f

Note that if you are using this technique for a command that produces output on STDERR, you should redirect it to /dev/null, otherwise adb will include STDERR in its STDOUT corrupting your output. For example, if you are trying to backup and compress a directory:

adb exec-out "tar -zcf - /system 2>/dev/null" > system.tar.gz

### 解决 ADB 截图破损问题 当使用 `adb exec-out screencap` 命令从 Android 设备获取截图时,图片可能因传输过程中的换行符处理不当而破损。以下是解决该问题的具体方法。 #### 方法一:通过命令管道删除多余的换行符 在 Windows 系统中,二进制数据流中的换行符 `\n` 被替换为 `\r\n`,从而破坏了 PNG 文件的格式。可以通过在命令管道中添加 `tr -d '\r'` 来删除所有 `\r` 字符,避免文件损坏[^1]。 ```bash adb exec-out screencap -p | tr -d '\r' > screenshot.png ``` #### 方法二:直接保存到设备并拉取文件 另一种解决方案是让设备直接将截图保存到其内部存储中,然后通过 ADB 拉取文件。这种方法避免了直接通过管道传输二进制数据,减少了因换行符处理不当导致的问题[^2]。 ```bash adb shell screencap /sdcard/screenshot.png adb pull /sdcard/screenshot.png . adb shell rm /sdcard/screenshot.png ``` #### 方法三:使用 Python 脚本修复图片 如果截图已经传输到电脑但出现破损,可以使用 Python 脚本对图片进行修复。脚本会将二进制数据流中的 `\r\n` 替换为 `\n`,从而恢复图片的完整性[^4]。 ```python def convert_img(path): with open(path, "br") as f: bys = f.read() bys_ = bys.replace(b"\r\n", b"\n") # 将 "\r\n" 替换为 "\n" with open(path, "bw") as f: f.write(bys_) ``` #### 方法四:按时间戳命名并保存截图 为了更方便地管理截图文件,可以结合时间戳生成唯一的文件名,并通过以下命令保存截图[^3]。 ```bash adb exec-out screencap -p > C:\Users\XXX\Desktop\%DATE:~0,4%-%DATE:~5,2%-%DATE:~8,2%-%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%.png ``` ### 注意事项 - 确保设备和电脑之间的连接稳定,避免因网络中断导致数据丢失。 - 在执行命令前,确认目标路径具有足够的存储空间和写入权限。 - 如果需要频繁截图,建议编写脚本来自动化这一过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值