7

我正在 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 应用程序,需要字节

4

2 回答 2

8

简单的答案是:

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()
于 2013-10-05T03:38:26.287 回答
1

fromstring 方法在 PIL 中已被弃用,取而代之的是 from bytes

于 2021-10-01T04:34:10.813 回答