You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python PIL库将libvirt流截图转换为其他格式图像?

实现方案

首先安装依赖库:
pip install pillow libvirt-python


修正后可直接运行的代码

import sys
import libvirt
import io
from PIL import Image

domName = 'TestAppliance'
conn = None
try:
    conn = libvirt.open("qemu:///system")
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)

dom = None
try:
    dom = conn.lookupByName(domName)
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)

stream = conn.newStream()
# 修正原代码的变量名错误:domain改为dom
imageType = dom.screenshot(stream, 0)

# 所有字节写入内存缓冲区,不生成中间PPM文件
img_buffer = io.BytesIO()
streamBytes = stream.recv(262120)
while streamBytes != b'':
    img_buffer.write(streamBytes)
    streamBytes = stream.recv(262120)

# 重置缓冲区指针到头部,供PIL解析
img_buffer.seek(0)
# 直接读取PPM流转存为PNG,开启优化压缩
with Image.open(img_buffer) as img:
    save_path = f"Screenshot of {dom.name()}.png"
    img.save(save_path, format="PNG", optimize=True)
    print(f'截图已保存至: {save_path},原始流格式为: {imageType}')

stream.finish()
conn.close()
exit(0)

方案说明

  • 全程在内存中处理流数据,无本地中间文件生成,减少IO冗余
  • 转换后的PNG格式体积仅为原PPM格式的1/10左右,常规虚拟机桌面截图大小可控制在几百KB
  • 如需更小体积可改为保存为WebP格式,将save方法参数调整为format="WebP", quality=80即可

内容的提问来源于stack exchange,提问作者PatrickF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 09:54:05