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

Python 3中如何将PIL图像正确转换为wxImage

问题根因

你搜到的旧参考代码运行报错,是因为现行维护版本的Pillow(即原PIL库)早已废弃并移除了Image对象的tostring()方法,该方法在新版本中对应替换为tobytes(),网上流传的老旧教程未跟进版本适配,直接照搬就会触发方法不存在的错误。

修正方案

全程不需要调用任何外部应用,直接在Python代码内部即可完成PIL图像到wxImage的转换、展示,核心转换逻辑修正如下:

# size参数直接从PIL图像对象取,避免尺寸不匹配
width, height = MyPILImage.size
mywxImage = wx.EmptyImage(width, height)
myPILImageRGB = MyPILImage.convert('RGB')
# 替换废弃的tostring()为tobytes()获取原始像素流
myPILImageData = myPILImageRGB.tobytes()
mywxImage.SetData(myPILImageData)
完整运行示例

以下是包含窗口加载、图像渲染的最小可运行代码,可直接复用实现内部图像展示:

import wx
from PIL import Image

class ImageDisplayFrame(wx.Frame):
    def __init__(self, pil_img, *args, **kw):
        super().__init__(*args, **kw)
        img_w, img_h = pil_img.size
        # 完成PIL到wxImage的转换
        display_img = wx.EmptyImage(img_w, img_h)
        display_img.SetData(pil_img.convert('RGB').tobytes())
        # 处理带透明通道的PNG等图像
        if pil_img.mode == 'RGBA':
            alpha_data = pil_img.convert('RGBA').tobytes()[3::4]
            display_img.SetAlpha(alpha_data)
        # 渲染到位图组件展示
        wx.StaticBitmap(self, -1, display_img.ConvertToBitmap())
        self.SetSize(wx.Size(img_w, img_h))

if __name__ == "__main__":
    app = wx.App()
    # 替换为你自己的PIL图像加载/处理逻辑
    target_pil_img = Image.open("your_image_path.png")
    frame = ImageDisplayFrame(target_pil_img, None, title="图像展示")
    frame.Show()
    app.MainLoop()

适配提示:如果传入的是Pillow生成的内存中图像(比如绘图、裁剪、滤镜处理后的图像对象),不需要保存到本地磁盘,直接传入上述方法即可完成渲染,全程无外部程序调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.19 16:15:45