【问题标题】:Python: process image and save to file streamPython:处理图像并保存到文件流
【发布时间】:2019-02-23 23:08:22
【问题描述】:
我需要使用 python 处理图像(应用过滤器和其他转换),然后使用 HTTP 将其提供给用户。现在,我正在使用 BaseHTTPServer 和 PIL。
问题是,PIL 不能直接写入文件流,所以我必须写入一个临时文件,然后读取该文件,以便将其发送给服务用户。
是否有任何 Python 图像处理库可以将 JPEG 直接输出到 I/O(类文件)流?有没有办法让 PIL 做到这一点?
【问题讨论】:
标签:
python
image-processing
python-imaging-library
【解决方案1】:
使用内存中的二进制文件对象io.BytesIO:
from io import BytesIO
imagefile = BytesIO()
animage.save(imagefile, format='PNG')
imagedata = imagefile.getvalue()
这在 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()
StringIO / cStringIO 是相同原理的较旧的遗留实现。