[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Displaying real time streaming images
Arthur Elsenaar wrote:
newbie question; how do I go about displaying arbitrary images coming in
over a socket as they arrive. I see PIL has some functions to read from
a buffer and has a parser to convert different formats, but I am at a
loss how to fit it all together as I am still learning. Also I suspect
it can be done solely in pygame?
Can someone help me out on this, so I can understand what's needed?
Maybe there's an example somewhere that I haven't found?
Pygame can load an image from any Python "file-like" object. This works
for most Python streams. Unfortunately, SDL's image loaders require the
stream to support seeking, so you'll need to create a temporary buffer.
>>> import pygame, urllib2, StringIO
>>> stream = urllib2.urlopen('http://pygame.org/docs/pygame_tiny.gif')
>>> pygame.image.load(stream)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
pygame.error: Can't seek in this data source
>>> stream = urllib2.urlopen('http://pygame.org/docs/pygame_tiny.gif')
>>> buffer = StringIO.StringIO(stream.read())
>>> pygame.image.load(buffer)
<Surface(200x60x8 SW)>
This technique will work for loading images from Zip archives and more.
Also, don't mistake this for "progressive" image loading, where you can
start to preview an image downloading over a slow link. Dropping the
source into a StringIO buffer will wait until the entire stream has been
read before continuing.
If you are sending raw image data over a socket, you should use calls
like pygame.image.tostring() and pygame.image.fromstring(). These
transfer the image to a large binary string, which can be sent over the
socket, or even exchanged with PIL's or PyopenGL's matching functions.