我正在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应用程序
简单的答案是:
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()
谢谢,我想我忘了提到管道的另一端是一个期待字节的.NET应用程序。该
tostring
如果收款人是在Python的工作,当然很好。@jhfelectric这两个都是原始字节的字符串,等同于您从中获得的字符串
open(name, "rb")