如何将pygame Surface作为图像保存到内存(而不是磁盘) [英] How to save pygame Surface as an image to memory (and not to disk)

查看:72
本文介绍了如何将pygame Surface作为图像保存到内存(而不是磁盘)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Raspberry PI 上开发一个对时间要求严格的应用程序,我需要通过网络发送图像.当我的图像被捕获时,我这样做:

I am developing a time-critical app on a Raspberry PI, and I need to send an image over the wire. 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.

感谢您的建议.

线路的另一端是一个需要字节的 .NET 应用程序

The other side of the wire is a .NET app expecting bytes

推荐答案

简单的答案是:

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

好像数据已经写好了,但是我不知道如何告诉pygame在保存到StringIO时使用什么格式.所以我们使用迂回的方式.

Seems like the data was written, but I have no idea how to tell pygame what format to use when saving to a 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()

这篇关于如何将pygame Surface作为图像保存到内存(而不是磁盘)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆