如何用pygame显示PIL图像?
how to display PIL image with pygame?
我正在尝试通过 wifi 从我的 raspberry pi 播放一些视频流。我使用了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
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')
Sloth 的回答对于较新版本的 Pygame 是不正确的。 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')
我正在尝试通过 wifi 从我的 raspberry pi 播放一些视频流。我使用了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
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')
Sloth 的回答对于较新版本的 Pygame 是不正确的。 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')