此代码在我的Ubuntu系统上运行良好,但是当我在Windows(基于7 x64)上运行时,图像不会显示。
此代码是更复杂系统的一部分,需要枕头将图像平滑地组合成所需格式
有人可以帮忙吗?我可能会缺少依赖关系吗?
import wx
from PIL import Image
class Example(wx.Frame):
"""
class description
"""
def __init__(self):
"""
initialise form
"""
wx.Frame.__init__(self, None, -1, 'Title', size=(600, 600))
sizer = wx.BoxSizer(wx.HORIZONTAL)
bitmap = wx.Bitmap('circle.png', wx.BITMAP_TYPE_PNG)
image = bitmap.ConvertToImage()
image = self.image_to_pil(image)
static_bitmap = self.static_bitmap_from_pil_image(self, image)
sizer.Add(static_bitmap)
self.SetSizer(sizer)
self.Centre()
self.Layout()
@staticmethod
def static_bitmap_from_pil_image(caller, pil_image):
wx_image = wx.EmptyImage(pil_image.size[0], pil_image.size[1])
wx_image.SetData(pil_image.convert("RGB").tobytes())
wx_image.SetAlphaData(pil_image.convert("RGBA").tobytes()[3::4])
bitmap = wx.BitmapFromImage(wx_image)
static_bitmap = wx.StaticBitmap(caller, wx.ID_ANY, wx.NullBitmap)
static_bitmap.SetBitmap(bitmap)
return static_bitmap
@staticmethod
def image_to_pil(image):
"""Convert wx.Image to PIL Image."""
width, height = image.GetSize()
data = image.GetData()
red_image = Image.new("L", (width, height))
red_image.frombytes(data[0::3])
green_image = Image.new("L", (width, height))
green_image.frombytes(data[1::3])
blue_image = Image.new("L", (width, height))
blue_image.frombytes(data[2::3])
if image.HasAlpha():
alpha_image = Image.new("L", (width, height))
alpha_image.frombytes(image.GetAlphaData())
pil_image = Image.merge('RGBA', (red_image, green_image, blue_image, alpha_image))
else:
pil_image = Image.merge('RGB', (red_image, green_image, blue_image))
return pil_image
if __name__ == '__main__':
"""
initialise application
"""
simple_screen_app = wx.App()
main_frame = Example()
main_frame.Show(True)
simple_screen_app.MainLoop()
答案 0 :(得分:1)
我已注释掉了这行
wx_image.SetAlphaData(pil_image.convert("RGBA").tobytes()[3::4])
并且有效
答案 1 :(得分:0)
wx.Image.SetAlphaData在较新的wxPython版本中被删除 使用:
Platform Windows
Windows 10.0.17134
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)]
Wx 4.0.4
Pillow 6.1.0
我设法使用此转换方法在wx.StaticBitmap中显示图像:
def pil_image_to_wx_image(pil_img, copy_alpha=True):
"""
Image conversion from a Pillow Image to a wx.Image.
"""
orig_width, orig_height = pil_img.size
wx_img = wx.Image(orig_width, orig_height)
wx_img.SetData(pil_img.convert('RGB').tobytes())
if copy_alpha and (pil_img.mode[-1] == 'A'):
alpha = pil_img.getchannel("A").tobytes()
wx_img.InitAlpha()
for i in range(orig_width):
for j in range(orig_height):
wx_img.SetAlpha(i, j, alpha[i + j * orig_width])
return wx_img