news 2026/4/4 11:42:01

wsl给windows桌面截图

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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 = 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), )
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/29 3:29:58

HS2-HF_Patch工具:全方位优化Honey Select 2游戏体验的解决方案

HS2-HF_Patch工具:全方位优化Honey Select 2游戏体验的解决方案 【免费下载链接】HS2-HF_Patch Automatically translate, uncensor and update HoneySelect2! 项目地址: https://gitcode.com/gh_mirrors/hs/HS2-HF_Patch HS2-HF_Patch是一款专为Honey Selec…

作者头像 李华
网站建设 2026/4/2 10:26:30

掌握4个Python开发提速技巧:从效率瓶颈到流畅编码

掌握4个Python开发提速技巧:从效率瓶颈到流畅编码 【免费下载链接】spyder Official repository for Spyder - The Scientific Python Development Environment 项目地址: https://gitcode.com/gh_mirrors/sp/spyder 还在为代码调试耗时、格式混乱、重复劳动…

作者头像 李华
网站建设 2026/4/3 5:22:58

Cursor解除请求限制优化方案:从提示拦截到性能提升的完整指南

Cursor解除请求限制优化方案:从提示拦截到性能提升的完整指南 【免费下载链接】go-cursor-help 解决Cursor在免费订阅期间出现以下提示的问题: Youve reached your trial request limit. / Too many free trial accounts used on this machine. Please upgrade to p…

作者头像 李华
网站建设 2026/4/4 2:16:20

不踩雷! 9个降AI率工具测评:专科生必看的降AIGC神器推荐

在如今的学术写作中,AI生成内容(AIGC)已经成为一种常见现象,但随之而来的高AIGC率和查重问题也让不少学生感到困扰。尤其是对于专科生来说,论文的原创性和逻辑性要求同样严格,如何在保证语义通顺的前提下有…

作者头像 李华
网站建设 2026/3/15 22:14:57

直播录制工具全攻略:开源解决方案 BililiveRecorder 高效捕获指南

直播录制工具全攻略:开源解决方案 BililiveRecorder 高效捕获指南 【免费下载链接】BililiveRecorder 录播姬 | mikufans 生放送录制 项目地址: https://gitcode.com/gh_mirrors/bi/BililiveRecorder 在数字内容创作蓬勃发展的今天,直播内容的实时…

作者头像 李华
网站建设 2026/3/17 2:49:21

政务OA系统如何通过源码改造提升Excel导入性能?

CMS企业官网Word导入功能开发实录 需求分析与技术评估 客户核心需求 支持Office文档(Word/Excel/PPT/PDF)导入并保留完整样式实现Word内容一键粘贴功能公式处理(LaTeX/MathType)转换MathML图片自动上传至阿里云OSS高龄用户友好型操作设计 技术栈现状 前端:Vue2…

作者头像 李华