Python:处理图像并保存到文件流

Ela*_*ssa 5 python image-processing python-imaging-library

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

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

有没有可以将JPEG直接输出到I/O(类文件)流的python图像处理库?有没有办法让PIL这样做?

Mar*_*ers 11

使用内存中的二进制文件对象io.BytesIO:

from io import BytesIO

imagefile = BytesIO()
animage.save(imagefile, format='PNG')
imagedata = imagefile.getvalue()
Run Code Online (Sandbox Code Playgroud)

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

仅在Python 2上,您还可以使用内存中的文件对象模块StringIO,或者更快的C编码等效模块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()
Run Code Online (Sandbox Code Playgroud)

StringIO/ cStringIO是相同原则的旧的,遗留的实现.