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 = f"screenshot_{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], check=True, stdout=subprocess.PIPE, stderr=subprocess.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, format="PNG") 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, format="PNG", optimize=True) # === 5. 返回结果 === img_byte_arr = io.BytesIO() full_image.save(img_byte_arr, format="PNG", optimize=True) base64_str = base64.b64encode(img_byte_arr.getvalue()).decode("utf-8") return ImageBlock( type="image", source=Base64Source(type="base64", media_type="image/png", data=base64_str), )wsl给windows桌面截图
张小明
前端开发工程师
Vue3代码编辑器实战指南:基于vue-codemirror的高效集成与性能优化
Vue3代码编辑器实战指南:基于vue-codemirror的高效集成与性能优化 【免费下载链接】vue-codemirror codemirror code editor component for vuejs 项目地址: https://gitcode.com/gh_mirrors/vu/vue-codemirror 在现代Web开发中,Vue组件已成为构建…
Lcov RPM包跨系统安装故障排查日志
Lcov RPM包跨系统安装故障排查日志 【免费下载链接】lcov LCOV 项目地址: https://gitcode.com/gh_mirrors/lc/lcov 问题现象记录 2023年11月15日,收到用户反馈在Rocky Linux 8.7系统上安装lcov-2.1-1.noarch.rpm时出现兼容性错误。执行dnf install lcov-2.…
熵减系统测试:局部逆转热力学定律的代价
一、热力学基础:熵增铁律与局部逆转的代价 1.1 熵增定律的不可逆性 热力学第二定律表明:孤立系统的总熵永不减少(ΔS ≥ 0)。在软件测试系统中,熵增表现为: 用例冗余度:重复测试用例以年均37%速…
塞尔达传说存档转换黑科技:Botw Save Manager神器助你跨平台无缝迁移
塞尔达传说存档转换黑科技:Botw Save Manager神器助你跨平台无缝迁移 【免费下载链接】BotW-Save-Manager BOTW Save Manager for Switch and Wii U 项目地址: https://gitcode.com/gh_mirrors/bo/BotW-Save-Manager 《塞尔达传说:旷野之息》玩家…
互联网大厂Java求职面试实战:微服务架构与AI应用的深度探讨
互联网大厂Java求职面试实战:微服务架构与AI应用的深度探讨 在智慧物流场景下,互联网大厂Java求职面试现场,严肃的面试官与搞笑的水货程序员谢飞机展开了一场精彩的技术问答。面试涵盖Java核心版本、构建工具、微服务架构、安全框架、消息队列…
如何解决ComfyUI工作流加载异常:新手友好的快速修复方案
如何解决ComfyUI工作流加载异常:新手友好的快速修复方案 【免费下载链接】ComfyUI-Impact-Pack 项目地址: https://gitcode.com/gh_mirrors/co/ComfyUI-Impact-Pack ComfyUI工作流加载异常是使用Impact-Pack扩展时常见的技术问题,表现为工作流文…