【问题标题】:how to display PIL image with pygame?如何用 pygame 显示 PIL 图像?
【发布时间】:2015-10-20 19:08:54
【问题描述】:

我正在尝试通过 wifi 从我的树莓派做一些视频流。我使用了 pygame,因为我还必须在我的项目中使用游戏手柄。不幸的是,我坚持显示收到的帧。很快:我得到 jpeg 帧,用 PIL 打开它,转换为字符串 - 之后我可以从字符串加载图像

image_stream = io.BytesIO()
...
frame_1 = Image.open(image_stream) 
f = StringIO.StringIO()
frame_1.save(f, "JPEG")
data = f.getvalue()
frame = pygame.image.fromstring(frame_1,image_len,"RGB")
screen.fill(white)
screen.blit(frame, (0,0))
pygame.display.flip()

错误是:

Traceback (most recent call last):
  File "C:\Users\defau_000\Desktop\server.py", line 57, in <module>
    frame = pygame.image.fromstring(frame_1,image_len,"RGB")
TypeError: must be str, not instance

【问题讨论】:

    标签: python pygame python-imaging-library


    【解决方案1】:

    对于较新版本的 Pygame,Sloth 的回答是不正确的。 tostring() 定义已弃用。这是 Python 3.6、PIL 5.1.0、Pygame 1.9.3 的工作变体:

    raw_str = frame_1.tobytes("raw", 'RGBA')
    pygame_surface = pygame.image.fromstring(raw_str, size, 'RGBA')
    

    【讨论】:

      【解决方案2】:

      pygame.image.fromstring 的第一个参数必须是 str

      所以当frame_1 是您的PIL 图像时,将其转换为带有tostring 的字符串,并使用pygame.image.fromstring 加载此字符串。

      您必须知道图像的大小才能使其正常工作。

      raw_str = frame_1.tostring("raw", 'RGBA')
      pygame_surface = pygame.image.fromstring(raw_str, size, 'RGBA')
      

      【讨论】:

        猜你喜欢
        • 2020-05-31
        • 2022-01-23
        • 2012-12-20
        • 1970-01-01
        • 1970-01-01
        • 2012-09-16
        • 2016-05-29
        • 1970-01-01
        • 2020-08-28
        相关资源
        最近更新 更多