Python:处理图像并保存到文件流 [英] Python: process image and save to file stream

查看:485
本文介绍了Python:处理图像并保存到文件流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用python处理图像(应用过滤器和其他转换),然后使用HTTP将其提供给用户.现在,我正在使用BaseHTTPServer和PIL.

I need to process an image (apply filters and other transformation) using python and then serve it to the user using HTTP. Right now, I'm using BaseHTTPServer and PIL.

问题是,PIL无法直接写入文件流,因此我必须先写入一个临时文件,然后再读取此文件,然后才能将其发送给服务的用户.

Problem is, PIL can't write directly into file streams, so I have to write into a temporary file, and then read this file so I could send it to the user of the service.

是否有适用于python的图像处理库,可以直接将JPEG输出到I/O(类似文件)流?有没有办法让PIL做到这一点?

Are there any image processing libraries for python that can output JPEG directly to I/O (file-like) streams? is there a way to make PIL do that?

推荐答案

使用内存中的二进制文件对象

Use the in-memory binary file object io.BytesIO:

from io import BytesIO

imagefile = BytesIO()
animage.save(imagefile, format='PNG')
imagedata = imagefile.getvalue()

这在Python 2和Python 3上都可用,因此应该是首选.

This is available on both Python 2 and Python 3, so should be the preferred choice.

仅在Python 2上,您还可以使用内存文件对象模块 StringIO ,或者更快的C编码等效 cStringIO :

On Python 2 only, you can also use the in-memory file object module StringIO, or it's faster C-coded equivalent cStringIO:

from cStringIO import StringIO

imagefile = StringIO()  # writable object

# save to open filehandle, so specifying the expected format is required
animage.save(imagefile, format='PNG')
imagedata = imagefile.getvalue()

StringIO / cStringIO 是具有相同原理的较旧的传统实现.

StringIO / cStringIO is the older, legacy implementation of the same principle.

这篇关于Python:处理图像并保存到文件流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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