wsl给windows桌面截图

📅 发布时间:2026/7/8 18:37:30 👁️ 浏览次数:
wsl给windows桌面截图
import io import base64 import os import shutil import subprocess from datetime import datetime from agentscope.message import ImageBlock, Base64Source from PIL import Image def take_screenshot() - ImageBlock: [WSL 强制 Windows 版] 直接调用 Windows PowerShell 截图绕过 WSL 图形层的所有问题。 保存到 output/screenshot/ 文件夹并返回 ImageBlock。 # 1. 准备目录 screenshot_dir output/screenshot if os.path.exists(screenshot_dir): for filename in os.listdir(screenshot_dir): file_path os.path.join(screenshot_dir, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print(f⚠️ 无法删除 {file_path}: {e}) else: os.makedirs(screenshot_dir) # 2. 准备文件路径 timestamp datetime.now().strftime(%Y%m%d_%H%M%S) filename fscreenshot_{timestamp}.png # 获取当前工作目录的绝对路径 abs_path os.path.abspath(screenshot_dir) filepath os.path.join(abs_path, filename) # 3. 调用 Windows PowerShell 截图 # 使用 wslpath 将 Linux 路径转换为 Windows 路径 try: win_filepath subprocess.check_output([wslpath, -w, filepath]).decode(utf-8).strip() except Exception: # 如果 wslpath 失败尝试简单的字符串替换作为保底 # 注意这通常只在简单路径下有效复杂路径可能出错 win_filepath filepath.replace(/, \\) print(f 正在调用 Windows 截图工具保存至: {win_filepath}) try: # 构造 PowerShell 脚本 # 逻辑加载 .NET - 获取主屏边界 - 创建位图 - 复制屏幕 - 保存 ps_script f Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; $bounds [System.Windows.Forms.Screen]::PrimaryScreen.Bounds; $bmp New-Object System.Drawing.Bitmap ($bounds.width, $bounds.height); $graphics [System.Drawing.Graphics]::FromImage($bmp); $graphics.CopyFromScreen($bounds.X, $bounds.Y, 0, 0, $bounds.size); $bmp.Save({win_filepath}, [System.Drawing.Imaging.ImageFormat]::Png); $graphics.Dispose(); $bmp.Dispose(); # 执行 PowerShell 命令 subprocess.run( [powershell.exe, -NoProfile, -ExecutionPolicy, Bypass, -Command, ps_script], checkTrue, stdoutsubprocess.PIPE, stderrsubprocess.PIPE ) # 等待文件写入完成跨文件系统写入可能需要一点时间 import time time.sleep(1) if not os.path.exists(filepath): raise FileNotFoundError(截图命令执行完毕但未找到文件。) except Exception as e: print(f❌ Windows 截图失败: {e}) # 生成黑色占位图 full_image Image.new(RGB, (1920, 1080), (0, 0, 0)) # 即使失败也尝试保存一下防止后续流程崩溃 try: full_image.save(filepath, formatPNG) except: pass else: print(✅ Windows 截图成功) try: full_image Image.open(filepath) except Exception as e: print(f⚠️ 无法打开截图文件: {e}) full_image Image.new(RGB, (1920, 1080), (0, 0, 0)) # 4. 调整大小 max_size 2048 if full_image.width max_size or full_image.height max_size: ratio min(max_size / full_image.width, max_size / full_image.height) new_w int(full_image.width * ratio) new_h int(full_image.height * ratio) full_image full_image.resize((new_w, new_h), Image.Resampling.LANCZOS) # 保存处理后的图片 full_image.save(filepath, formatPNG, optimizeTrue) # 5. 返回结果 img_byte_arr io.BytesIO() full_image.save(img_byte_arr, formatPNG, optimizeTrue) base64_str base64.b64encode(img_byte_arr.getvalue()).decode(utf-8) return ImageBlock( typeimage, sourceBase64Source(typebase64, media_typeimage/png, database64_str), )