adb-screencap.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env node
  2. /**
  3. * ADB 截图:将设备屏幕捕获到本地文件
  4. * 用法: node adb-screencap.js <deviceId> <outputPath>
  5. * 示例: node adb-screencap.js 192.168.2.5:5555 C:\temp\screen.png
  6. */
  7. const { spawnSync } = require('child_process')
  8. const path = require('path')
  9. const fs = require('fs')
  10. const config = require(path.join(__dirname, '..', '..', 'configs', 'config.js'))
  11. const projectRoot = path.resolve(__dirname, '..', '..')
  12. const adbPath = config.adbPath?.path
  13. ? path.resolve(projectRoot, config.adbPath.path)
  14. : path.join(projectRoot, 'lib', 'scrcpy-adb', 'adb.exe')
  15. const deviceId = process.argv[2]
  16. const outputPath = process.argv[3]
  17. if (!deviceId || !outputPath) {
  18. process.stderr.write('Usage: node adb-screencap.js <deviceId> <outputPath>\n')
  19. process.exit(1)
  20. }
  21. const deviceFlag = deviceId && deviceId.includes(':') ? ['-s', deviceId] : []
  22. const args = [...deviceFlag, 'exec-out', 'screencap', '-p']
  23. const result = spawnSync(adbPath, args, {
  24. encoding: null,
  25. timeout: 10000,
  26. maxBuffer: 16 * 1024 * 1024
  27. })
  28. if (result.error) {
  29. process.stderr.write(`screencap error: ${result.error.message}\n`)
  30. process.exit(1)
  31. }
  32. if (result.status !== 0) {
  33. process.stderr.write((result.stderr || result.stdout || Buffer.from('')).toString('utf8'))
  34. process.exit(1)
  35. }
  36. let data = result.stdout
  37. if (!data || data.length === 0) {
  38. process.stderr.write('screencap returned empty data\n')
  39. process.exit(1)
  40. }
  41. // 注意:不要对 PNG 做 \r\n 替换,会破坏 IDAT 压缩块导致 OpenCV/PIL 无法解析
  42. const dir = path.dirname(outputPath)
  43. if (!fs.existsSync(dir)) {
  44. fs.mkdirSync(dir, { recursive: true })
  45. }
  46. fs.writeFileSync(outputPath, data)
  47. process.stdout.write(outputPath)
  48. process.exit(0)