- Removed excessive blank lines in various Python scripts, markdown files, and configuration files to improve overall code clarity and maintainability. - Ensured consistent formatting throughout the project, contributing to a more organized codebase.
524 lines
17 KiB
Python
524 lines
17 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
# pyright: reportOptionalMemberAccess=false
|
||
"""
|
||
详细检查设备是否支持 JPEG 截图
|
||
测试各种可能的 JPEG 截图方法
|
||
"""
|
||
|
||
import os
|
||
import sys
|
||
import subprocess
|
||
import tempfile
|
||
import time
|
||
from datetime import datetime
|
||
from typing import Dict, List, Tuple, cast, IO
|
||
|
||
def get_adb_path() -> str:
|
||
"""获取 adb 路径"""
|
||
adb = os.environ.get("ADB_EXECUTABLE", "adb")
|
||
if adb.startswith('"') and adb.endswith('"'):
|
||
adb = adb[1:-1]
|
||
return adb
|
||
|
||
def get_device_info(device_id: str) -> Dict[str, str]:
|
||
"""获取设备信息"""
|
||
adb = get_adb_path()
|
||
info = {}
|
||
|
||
try:
|
||
# Android 版本
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "getprop", "ro.build.version.release"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3
|
||
)
|
||
info["android_version"] = result.stdout.strip() if result.returncode == 0 else "未知"
|
||
except:
|
||
info["android_version"] = "未知"
|
||
|
||
try:
|
||
# 设备型号
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "getprop", "ro.product.model"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3
|
||
)
|
||
info["model"] = result.stdout.strip() if result.returncode == 0 else "未知"
|
||
except:
|
||
info["model"] = "未知"
|
||
|
||
try:
|
||
# 制造商
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "getprop", "ro.product.manufacturer"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3
|
||
)
|
||
info["manufacturer"] = result.stdout.strip() if result.returncode == 0 else "未知"
|
||
except:
|
||
info["manufacturer"] = "未知"
|
||
|
||
return info
|
||
|
||
def check_root_access(device_id: str) -> bool:
|
||
"""检查 root 权限"""
|
||
adb = get_adb_path()
|
||
try:
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "su", "-c", "id"],
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
timeout=3,
|
||
capture_output=True,
|
||
)
|
||
return "uid=0" in result.stdout.decode('utf-8', errors='ignore')
|
||
except:
|
||
return False
|
||
|
||
def test_screencap_jpeg_direct(device_id: str) -> Tuple[bool, str, float]:
|
||
"""测试方法1: screencap 直接输出 JPEG(如果支持)"""
|
||
adb = get_adb_path()
|
||
tmp_file = os.path.join(tempfile.gettempdir(), "test_jpeg_direct.jpg")
|
||
|
||
# 测试各种可能的 JPEG 参数
|
||
test_commands = [
|
||
["exec-out", "screencap", "-j"], # 标准 JPEG 参数
|
||
["exec-out", "screencap", "--jpeg"], # 长参数
|
||
["exec-out", "screencap", "-f", "jpeg"], # 格式参数
|
||
["exec-out", "screencap", "-p", "-j"], # PNG + JPEG
|
||
["shell", "screencap", "-j", "/sdcard/test.jpg"], # shell 模式
|
||
]
|
||
|
||
for cmd in test_commands:
|
||
try:
|
||
if os.path.exists(tmp_file):
|
||
try:
|
||
os.remove(tmp_file)
|
||
except:
|
||
pass
|
||
|
||
start_time = time.time()
|
||
full_cmd = [adb, "-s", device_id] + cmd
|
||
|
||
if "exec-out" in cmd:
|
||
# 流式读取
|
||
process = subprocess.Popen(
|
||
full_cmd,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
|
||
if process.stdout is None:
|
||
continue
|
||
|
||
assert process.stdout is not None
|
||
stdout = cast(IO[bytes], process.stdout)
|
||
with open(tmp_file, "wb") as f:
|
||
while True:
|
||
chunk = stdout.read(65536) # type: ignore[union-attr]
|
||
if not chunk:
|
||
break
|
||
f.write(chunk)
|
||
|
||
return_code = process.wait(timeout=5)
|
||
else:
|
||
# shell 模式
|
||
result = subprocess.run(
|
||
full_cmd,
|
||
stdout=subprocess.DEVNULL,
|
||
stderr=subprocess.DEVNULL,
|
||
timeout=5,
|
||
)
|
||
return_code = result.returncode
|
||
|
||
if return_code == 0 and "shell" in cmd:
|
||
# 如果是 shell 模式,需要 pull
|
||
subprocess.run(
|
||
[adb, "-s", device_id, "pull", "/sdcard/test.jpg", tmp_file],
|
||
stdout=subprocess.DEVNULL,
|
||
stderr=subprocess.DEVNULL,
|
||
timeout=5,
|
||
)
|
||
|
||
elapsed = (time.time() - start_time) * 1000
|
||
|
||
if return_code == 0 and os.path.exists(tmp_file):
|
||
file_size = os.path.getsize(tmp_file)
|
||
# 检查是否是有效的 JPEG(检查文件头)
|
||
if file_size > 100:
|
||
with open(tmp_file, "rb") as f:
|
||
header = f.read(2)
|
||
if header == b'\xff\xd8': # JPEG 文件头
|
||
return True, f"命令: {' '.join(cmd)}", elapsed
|
||
|
||
except Exception as e:
|
||
continue
|
||
|
||
return False, "不支持直接 JPEG 输出", 0.0
|
||
|
||
def test_screencap_help(device_id: str) -> Dict[str, bool]:
|
||
"""检查 screencap 帮助信息,查看支持的参数"""
|
||
adb = get_adb_path()
|
||
result = {}
|
||
|
||
try:
|
||
# 获取 screencap 帮助信息
|
||
help_output = ""
|
||
try:
|
||
help_output += subprocess.run(
|
||
[adb, "-s", device_id, "shell", "screencap", "-h"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3,
|
||
).stdout
|
||
except:
|
||
pass
|
||
|
||
try:
|
||
help_output += subprocess.run(
|
||
[adb, "-s", device_id, "shell", "screencap", "--help"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3,
|
||
).stdout
|
||
except:
|
||
pass
|
||
|
||
# 检查是否包含 JPEG 相关参数
|
||
result["has_jpeg_flag"] = any(keyword in help_output.lower() for keyword in ["-j", "jpeg", "--jpeg"])
|
||
result["has_format_flag"] = any(keyword in help_output.lower() for keyword in ["-f", "format", "--format"])
|
||
result["has_quality_flag"] = any(keyword in help_output.lower() for keyword in ["-q", "quality", "--quality"])
|
||
|
||
except:
|
||
result["has_jpeg_flag"] = False
|
||
result["has_format_flag"] = False
|
||
result["has_quality_flag"] = False
|
||
|
||
return result
|
||
|
||
def test_device_tools(device_id: str) -> Dict[str, bool]:
|
||
"""检查设备上是否有可用的转换工具"""
|
||
adb = get_adb_path()
|
||
tools = {}
|
||
|
||
# 检查 ImageMagick convert
|
||
try:
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "which", "convert"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3,
|
||
)
|
||
tools["imagemagick"] = result.returncode == 0 and result.stdout.strip() != ""
|
||
except:
|
||
tools["imagemagick"] = False
|
||
|
||
# 检查 /data/local/tmp/convert
|
||
try:
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "test", "-f", "/data/local/tmp/convert"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3,
|
||
)
|
||
tools["imagemagick_tmp"] = result.returncode == 0
|
||
except:
|
||
tools["imagemagick_tmp"] = False
|
||
|
||
# 检查 Python
|
||
try:
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "which", "python3"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3,
|
||
)
|
||
tools["python3"] = result.returncode == 0 and result.stdout.strip() != ""
|
||
except:
|
||
tools["python3"] = False
|
||
|
||
# 检查 Python (python)
|
||
try:
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "which", "python"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3,
|
||
)
|
||
tools["python"] = result.returncode == 0 and result.stdout.strip() != ""
|
||
except:
|
||
tools["python"] = False
|
||
|
||
# 检查 BusyBox
|
||
try:
|
||
result = subprocess.run(
|
||
[adb, "-s", device_id, "shell", "which", "busybox"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3,
|
||
)
|
||
tools["busybox"] = result.returncode == 0 and result.stdout.strip() != ""
|
||
except:
|
||
tools["busybox"] = False
|
||
|
||
return tools
|
||
|
||
def test_pc_conversion(device_id: str) -> Tuple[bool, str, float]:
|
||
"""测试方法2: PC 端转换(PNG -> JPEG)"""
|
||
try:
|
||
from PIL import Image
|
||
import io
|
||
except ImportError:
|
||
return False, "PIL/Pillow 未安装", 0.0
|
||
|
||
adb = get_adb_path()
|
||
tmp_jpg = os.path.join(tempfile.gettempdir(), "test_jpeg_pc.jpg")
|
||
|
||
try:
|
||
start_time = time.time()
|
||
|
||
# 流式接收 PNG
|
||
process = subprocess.Popen(
|
||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
|
||
if process.stdout is None:
|
||
return False, "无法创建进程输出流", 0.0
|
||
|
||
assert process.stdout is not None
|
||
stdout = cast(IO[bytes], process.stdout)
|
||
png_data = b""
|
||
while True:
|
||
chunk = stdout.read(65536) # type: ignore[union-attr]
|
||
if not chunk:
|
||
break
|
||
png_data += chunk
|
||
|
||
process.wait(timeout=10)
|
||
|
||
if len(png_data) < 100:
|
||
return False, "PNG 数据无效", 0.0
|
||
|
||
# 转换为 JPEG(RGBA 需要先转换为 RGB)
|
||
img = Image.open(io.BytesIO(png_data))
|
||
if img.mode == 'RGBA':
|
||
# 创建白色背景
|
||
rgb_img = Image.new('RGB', img.size, (255, 255, 255))
|
||
rgb_img.paste(img, mask=img.split()[3]) # 使用 alpha 通道作为 mask
|
||
img = rgb_img
|
||
elif img.mode != 'RGB':
|
||
img = img.convert('RGB')
|
||
|
||
jpeg_data = io.BytesIO()
|
||
img.save(jpeg_data, format='JPEG', quality=85, optimize=True)
|
||
|
||
with open(tmp_jpg, "wb") as f:
|
||
f.write(jpeg_data.getvalue())
|
||
|
||
elapsed = (time.time() - start_time) * 1000
|
||
file_size = os.path.getsize(tmp_jpg)
|
||
|
||
return True, f"PC 端转换成功,文件大小: {file_size/1024:.1f}KB", elapsed
|
||
|
||
except Exception as e:
|
||
return False, f"PC 端转换失败: {str(e)}", 0.0
|
||
|
||
def test_device_conversion(device_id: str) -> Tuple[bool, str, float]:
|
||
"""测试方法3: 设备端转换(如果工具可用)"""
|
||
adb = get_adb_path()
|
||
tools = test_device_tools(device_id)
|
||
|
||
# 测试 ImageMagick
|
||
if tools.get("imagemagick") or tools.get("imagemagick_tmp"):
|
||
convert_path = "/data/local/tmp/convert" if tools.get("imagemagick_tmp") else "convert"
|
||
|
||
try:
|
||
start_time = time.time()
|
||
tmp_file = os.path.join(tempfile.gettempdir(), "test_jpeg_device.jpg")
|
||
|
||
# 使用 shell 命令组合
|
||
cmd = f"screencap -p | {convert_path} - -quality 85 jpg:-"
|
||
process = subprocess.Popen(
|
||
[adb, "-s", device_id, "exec-out", "sh", "-c", cmd],
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
|
||
if process.stdout is None:
|
||
raise Exception("无法创建进程输出流")
|
||
|
||
assert process.stdout is not None
|
||
stdout = cast(IO[bytes], process.stdout)
|
||
with open(tmp_file, "wb") as f:
|
||
while True:
|
||
chunk = stdout.read(65536) # type: ignore[union-attr]
|
||
if not chunk:
|
||
break
|
||
f.write(chunk)
|
||
|
||
return_code = process.wait(timeout=10)
|
||
elapsed = (time.time() - start_time) * 1000
|
||
|
||
if return_code == 0 and os.path.exists(tmp_file):
|
||
file_size = os.path.getsize(tmp_file)
|
||
if file_size > 100:
|
||
with open(tmp_file, "rb") as f:
|
||
header = f.read(2)
|
||
if header == b'\xff\xd8':
|
||
return True, f"ImageMagick 转换成功,文件大小: {file_size/1024:.1f}KB", elapsed
|
||
except Exception as e:
|
||
pass
|
||
|
||
return False, "设备端无可用转换工具", 0.0
|
||
|
||
def main():
|
||
"""主函数"""
|
||
print("=" * 70)
|
||
print("设备 JPEG 截图支持检查工具")
|
||
print("=" * 70)
|
||
print()
|
||
|
||
# 获取设备ID
|
||
device_id = None
|
||
if len(sys.argv) > 1:
|
||
device_id = sys.argv[1]
|
||
else:
|
||
device_id = os.environ.get("ANDROID_DEVICE_ID")
|
||
|
||
if not device_id:
|
||
# 尝试从 adb devices 获取
|
||
try:
|
||
adb = get_adb_path()
|
||
result = subprocess.run(
|
||
[adb, "devices"],
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=3,
|
||
)
|
||
lines = result.stdout.strip().split('\n')[1:] # 跳过第一行
|
||
devices = [line.split()[0] for line in lines if line.strip() and 'device' in line]
|
||
if len(devices) == 1:
|
||
device_id = devices[0]
|
||
elif len(devices) > 1:
|
||
print(f"[INFO] 发现多个设备: {', '.join(devices)}")
|
||
print(f"[INFO] 使用第一个设备: {devices[0]}")
|
||
device_id = devices[0]
|
||
except:
|
||
pass
|
||
|
||
if not device_id:
|
||
print("[ERROR] 未找到设备ID")
|
||
print("使用方法: python check_jpeg_support.py [设备ID]")
|
||
print("或设置环境变量: set ANDROID_DEVICE_ID=设备ID")
|
||
return
|
||
|
||
print(f"设备ID: {device_id}")
|
||
print()
|
||
|
||
# 获取设备信息
|
||
print("1. 设备信息")
|
||
print("-" * 70)
|
||
info = get_device_info(device_id)
|
||
print(f" 制造商: {info.get('manufacturer', '未知')}")
|
||
print(f" 型号: {info.get('model', '未知')}")
|
||
print(f" Android 版本: {info.get('android_version', '未知')}")
|
||
|
||
has_root = check_root_access(device_id)
|
||
print(f" Root 权限: {'是' if has_root else '否'}")
|
||
print()
|
||
|
||
# 检查 screencap 帮助信息
|
||
print("2. screencap 命令支持检查")
|
||
print("-" * 70)
|
||
help_info = test_screencap_help(device_id)
|
||
print(f" 支持 -j/--jpeg 参数: {'是' if help_info.get('has_jpeg_flag') else '否'}")
|
||
print(f" 支持 -f/--format 参数: {'是' if help_info.get('has_format_flag') else '否'}")
|
||
print(f" 支持质量参数: {'是' if help_info.get('has_quality_flag') else '否'}")
|
||
print()
|
||
|
||
# 测试直接 JPEG 输出
|
||
print("3. 测试直接 JPEG 截图")
|
||
print("-" * 70)
|
||
success, msg, elapsed = test_screencap_jpeg_direct(device_id)
|
||
if success:
|
||
print(f" [OK] 支持直接 JPEG 输出")
|
||
print(f" 方法: {msg}")
|
||
print(f" 耗时: {elapsed:.0f}ms")
|
||
else:
|
||
print(f" [X] 不支持直接 JPEG 输出")
|
||
print(f" 原因: {msg}")
|
||
print()
|
||
|
||
# 检查设备工具
|
||
print("4. 设备端工具检查")
|
||
print("-" * 70)
|
||
tools = test_device_tools(device_id)
|
||
print(f" ImageMagick (convert): {'是' if tools.get('imagemagick') else '否'}")
|
||
print(f" ImageMagick (/data/local/tmp): {'是' if tools.get('imagemagick_tmp') else '否'}")
|
||
print(f" Python3: {'是' if tools.get('python3') else '否'}")
|
||
print(f" Python: {'是' if tools.get('python') else '否'}")
|
||
print(f" BusyBox: {'是' if tools.get('busybox') else '否'}")
|
||
print()
|
||
|
||
# 测试设备端转换
|
||
print("5. 测试设备端转换")
|
||
print("-" * 70)
|
||
success, msg, elapsed = test_device_conversion(device_id)
|
||
if success:
|
||
print(f" [OK] 设备端转换可用")
|
||
print(f" 方法: {msg}")
|
||
print(f" 耗时: {elapsed:.0f}ms")
|
||
else:
|
||
print(f" [X] 设备端转换不可用")
|
||
print(f" 原因: {msg}")
|
||
print()
|
||
|
||
# 测试 PC 端转换
|
||
print("6. 测试 PC 端转换")
|
||
print("-" * 70)
|
||
success, msg, elapsed = test_pc_conversion(device_id)
|
||
if success:
|
||
print(f" [OK] PC 端转换可用")
|
||
print(f" 方法: {msg}")
|
||
print(f" 耗时: {elapsed:.0f}ms")
|
||
else:
|
||
print(f" [X] PC 端转换不可用")
|
||
print(f" 原因: {msg}")
|
||
print()
|
||
|
||
# 总结
|
||
print("=" * 70)
|
||
print("检查结果总结")
|
||
print("=" * 70)
|
||
|
||
recommendations = []
|
||
|
||
direct_success, _, _ = test_screencap_jpeg_direct(device_id)
|
||
pc_success, _, _ = test_pc_conversion(device_id)
|
||
device_success, _, _ = test_device_conversion(device_id)
|
||
|
||
if direct_success:
|
||
recommendations.append("[OK] 设备支持直接 JPEG 截图(推荐使用)")
|
||
elif pc_success:
|
||
recommendations.append("[OK] 可以使用 PC 端转换方法(推荐,无需设备端工具)")
|
||
elif device_success:
|
||
recommendations.append("[OK] 可以使用设备端转换方法(需要安装工具)")
|
||
else:
|
||
recommendations.append("[X] 当前设备不支持 JPEG 截图,建议使用 PNG 格式")
|
||
|
||
for rec in recommendations:
|
||
print(f" {rec}")
|
||
|
||
print()
|
||
print("=" * 70)
|
||
|
||
if __name__ == "__main__":
|
||
main()
|
||
|