问题
I am trying to do some video stream from my raspberry pi over the wifi. I used pygame, because i also have to use gamepad in my project. Unfortunately I stucked on displaying received frame. Shortly: i get jpeg frame, open it with PIL, convert to string - after that i can load image from string
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()
and error is :
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
回答1:
The first argument to pygame.image.fromstring
has to be a str
.
So when frame_1
is your PIL image, convert it to a string with tostring
, and load this string with pygame.image.fromstring
.
You have to know the size of the image for this to work.
raw_str = frame_1.tostring("raw", 'RGBA')
pygame_surface = pygame.image.fromstring(raw_str, size, 'RGBA')
回答2:
Sloth's answer is incorrect for newer versions of Pygame. The tostring()
definition is deprecated. Here is a working variant for 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')
来源:https://stackoverflow.com/questions/33244928/how-to-display-pil-image-with-pygame