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桌面截图
张小明
前端开发工程师
探索STorM32 BGC:打造专业级影像稳定系统的开源方案
探索STorM32 BGC:打造专业级影像稳定系统的开源方案 【免费下载链接】storm32bgc 3-axis Brushless Gimbal Controller, based on STM32 32-bit microcontroller 项目地址: https://gitcode.com/gh_mirrors/st/storm32bgc 你是否正在寻找一款能够为无人机提…
3步攻克魔兽世界技能循环:GSE宏编译器解决方案
3步攻克魔兽世界技能循环:GSE宏编译器解决方案 【免费下载链接】GSE-Advanced-Macro-Compiler GSE is an alternative advanced macro editor and engine for World of Warcraft. It uses Travis for UnitTests, Coveralls to report on test coverage and the Curs…
突破网盘下载瓶颈:8大平台直链解析技术指南
突破网盘下载瓶颈:8大平台直链解析技术指南 【免费下载链接】Online-disk-direct-link-download-assistant 可以获取网盘文件真实下载地址。基于【网盘直链下载助手】修改(改自6.1.4版本) ,自用,去推广,无需…
如何通过MediaCrawler智能采集实现多平台数据获取新方案
如何通过MediaCrawler智能采集实现多平台数据获取新方案 【免费下载链接】MediaCrawler-new 项目地址: https://gitcode.com/GitHub_Trending/me/MediaCrawler-new 在信息爆炸的时代,企业和研究者常常面临这样的困境:如何高效、合规地获取分散在…
混合云架构中SolidWorks许可证的部署与管理策略
混合云架构中SolidWorks许可证的部署与管理策略一、问题的成因很多企业在向混合云架构转型的过程中,常常遇到关于SolidWorks许可证部署与管理方面的实际难题。这些难题往往源于对混合云环境理解不足,以及对SolidWorks授权机制的不熟悉。SolidWorks是一款…
YOLO26涨点改进 | 全网独家创新、Neck特征融合改进篇 | TGRS 2025顶刊 | 引入MGCM模态引导互补模块,含多种创新,融合浅层特征与深层特征,适合遥感目标检测、多模态融合,有效涨点
一、本文介绍 🔥本文给大家介绍使用MGCM模态引导互补模块改进 YOLO26 网络模型,其核心作用是在特征融合阶段显式建模不同模态或不同来源特征之间的互补关系,从而提升检测特征的判别性与稳定性。MGCM 通过多尺度、双向引导机制,使一类特征在另一类特征的约束下进行选择性增…