Warm tip: This article is reproduced from serverfault.com, please click

python-如何将pygame Surface作为图像保存到内存(而不是磁盘)

(python - How to save pygame Surface as an image to memory (and not to disk))

发布于 2013-10-05 01:55:32

我正在Raspberry PI上开发时间紧迫的应用程序,我需要通过网络发送图像。捕获图像后,我将执行以下操作:

# pygame.camera.Camera captures images as a Surface
pygame.image.save(mySurface,'temp.jpeg')
_img = open('temp.jpeg','rb')
_out = _img.read()
_img.close()
_socket.sendall(_out)

这不是很有效。我希望能够将表面作为图像保存在内存中并直接发送字节,而不必先将其保存到磁盘。

感谢你的任何建议。

编辑:另一端是期望字节的.NET应用程序

Questioner
jhfelectric
Viewed
0
kalhartt 2013-10-05 11:38:26

简单的答案是:

surf = pygame.Surface((100,200)) # I'm going to use 100x200 in examples
data = pygame.image.tostring(surf, 'RGBA')

并发送数据。但是我们要在发送前先压缩它。所以我尝试了这个

from StringIO import StringIO
data = StringIO()
pygame.image.save(surf, x)
print x.getvalue()

似乎是在写数据,但是我不知道如何告诉pygame在保存到StringIO时使用哪种格式。因此,我们使用回旋处的方式。

from StringIO import StringIO
from PIL import Image
data = pygame.image.tostring(surf, 'RGBA')
img = Image.fromstring('RGBA', (100,200), data)
zdata = StringIO()
img.save(zdata, 'JPEG')
print zdata.getvalue()