简体   繁体   English

如何将 pygame 表面作为图像保存到 memory(而不是磁盘)

[英]How to save pygame Surface as an image to memory (and not to disk)

I am developing a time-critical app on a Raspberry PI, and I need to send an image over the wire.我正在 Raspberry PI 上开发时间关键型应用程序,我需要通过网络发送图像。 When my image is captured, I am doing like this:当我的图像被捕获时,我是这样做的:

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

This is not very efficient.这不是很有效。 I would like to be able to save the surface as an image in memory and send the bytes directly without having to save it first to disk.我希望能够将表面保存为 memory 中的图像并直接发送字节,而不必先将其保存到磁盘。

Thanks for any advice.感谢您的任何建议。

EDIT: The other side of the wire is a .NET app expecting bytes编辑:线路的另一端是一个 .NET 应用程序,需要字节

The simple answer is:简单的答案是:

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

and just send the data.并发送数据。 But we want to compress it before we send it.但是我们想在发送之前压缩它。 So I tried this所以我试过这个

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

Seems like the data was written, but I have no idea how to tell pygame what format to use when saving to a StringIO.似乎数据已写入,但我不知道如何告诉 pygame 在保存到 StringIO 时使用什么格式。 So we use the roundabout way.所以我们使用迂回的方式。

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

the fromstring method has been deprecated in PIL and replaced with from bytes fromstring 方法已在 PIL 中弃用并替换为 from bytes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM