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

问题描述 投票:0回答:3

我正在 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 应用程序

python networking pygame raspberry-pi
3个回答
9
投票

简单的答案是:

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

1
投票

PIL 中已弃用 fromstring 方法,并替换为 from bytes


0
投票
import pygame

surface = pygame.image.load("shrubbery.svg")
# In case you change your mind and do want to save to disk already:
# pygame.image.save(surface, "shrubbery.webp")
bf = BytesIO()
pygame.image.save(surface, bf)
im = Image.open(bf)
im.show()
© www.soinside.com 2019 - 2024. All rights reserved.