screenshot.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { ipcMain } from 'electron';
  2. import { exec } from 'child_process';
  3. import { promisify } from 'util';
  4. import { getCachedAdbPath } from '../config.js';
  5. const execAsync = promisify(exec);
  6. // 抓取设备截屏(返回 base64 PNG/JPEG)
  7. export async function captureScreenshot(ipPort, options = {}) {
  8. if (!ipPort) {
  9. return { success: false, error: '缺少设备 ID' };
  10. }
  11. try {
  12. const adbPath = getCachedAdbPath();
  13. // 从选项或默认值获取参数
  14. const format = options.format || 'png'; // 'png' 或 'jpeg'
  15. const quality = options.quality || 80; // JPEG 质量 1-100
  16. const scale = options.scale || 1.0; // 缩放比例 0.1-1.0
  17. // 构建 screencap 命令
  18. let command = `${adbPath} -s ${ipPort} exec-out screencap`;
  19. // 根据格式选择参数
  20. if (format === 'jpeg') {
  21. // JPEG 格式(更小,延迟更低)
  22. command += ` -j ${quality}`;
  23. } else {
  24. // PNG 格式(默认)
  25. command += ' -p';
  26. }
  27. // 如果缩放比例不是 1.0,需要通过 shell 命令处理
  28. // 注意:screencap 本身不支持缩放,需要通过其他方式实现
  29. // 这里先实现基本功能,缩放可以在后续优化
  30. const { stdout } = await execAsync(command, {
  31. encoding: 'buffer',
  32. maxBuffer: 25 * 1024 * 1024,
  33. });
  34. return { success: true, data: stdout.toString('base64') };
  35. } catch (error) {
  36. console.error('截屏失败:', error);
  37. return { success: false, error: error.message };
  38. }
  39. }
  40. // 注册 IPC 处理器
  41. export function registerIpcHandlers() {
  42. // IPC 处理程序:抓取设备截屏(返回 base64 PNG/JPEG)
  43. ipcMain.handle('capture-screenshot', async (event, ipPort, options = {}) => {
  44. return await captureScreenshot(ipPort, options);
  45. });
  46. }