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

2024-06-25 23:53:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个时间关键的应用程序在树莓皮,我需要发送一个图像通过电线。 当我的图像被捕获时,我会这样做:

# 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应用程序


Tags: 图像应用程序img字节时间outpygametemp
1条回答
网友
1楼 · 发布于 2024-06-25 23:53:48

简单的答案是:

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()

相关问题 更多 >