我需要使用python处理图像(应用过滤器和其他转换),然后使用HTTP将其提供给用户。现在,我正在使用BaseHTTPServer和PIL。
问题是,PIL无法直接写入文件流,所以我必须写入一个临时文件,然后读取此文件,以便将其发送给服务的用户。
是否有任何可以将JPEG直接输出到I / O(类文件)流的图像处理库?有没有办法让PIL这样做?
答案 0 :(得分:10)
使用内存中的二进制文件对象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
是同一原则的旧版本。