Python PIL:如何将PNG图像写入字符串

Python PIL: how to write PNG image to string

我已经使用PIL生成了图像。 如何将其保存到内存中的字符串中?
Image.save()方法需要一个文件。

我想将几个这样的图像存储在字典中。


您可以使用BytesIO类来获取类似于文件的字符串包装。 BytesIO对象提供与文件相同的接口,但是将内容仅保存在内存中:

1
2
3
4
5
import io

with io.BytesIO() as output:
    image.save(output, format="GIF")
    contents = output.getvalue()

您必须使用format参数明确指定输出格式,否则PIL在尝试自动检测时会引发错误。

如果从文件加载图像,则图像的format参数包含原始文件格式,因此在这种情况下,可以使用format=image.format

在引入io模块之前的旧Python 2版本中,应该使用StringIO模块。


对于Python3,需要使用BytesIO:

1
2
3
4
5
6
7
8
9
10
from io import BytesIO
from PIL import Image, ImageDraw

image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0),"This text is drawn on image")

byte_io = BytesIO()

image.save(byte_io, 'PNG')

了解更多:http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image


某事的解决方案对我不起作用
因为在...

Imaging/PIL/Image.pyc line 1423 ->
raise KeyError(ext) # unknown
extension

它试图从文件名中的扩展名中检测格式,这在StringIO情况下不存在

您可以通过在参数中自行设置格式来绕过格式检测

1
2
3
4
5
6
import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()


save()可以采用类似文件的对象以及路径,因此您可以使用内存缓冲,例如StringIO:

1
2
3
buf= StringIO.StringIO()
im.save(buf, format= 'JPEG')
jpeg= buf.getvalue()


使用最新版本(自2017年中开始,Python 3.5和Pillow 4.0):

StringIO似乎不再像以前那样工作。 BytesIO类是处理此问题的正确方法。 Pillow的save函数期望将字符串作为第一个参数,并且令人惊讶地没有这样的StringIO。以下内容与较早的StringIO解决方案相似,但其位置为BytesIO。

1
2
3
4
5
6
from io import BytesIO
from PIL import Image

image = Image.open("a_file.png")
faux_file = BytesIO()
image.save(faux_file, 'png')


当您说"我想在词典中存储大量此类图像"时,尚不清楚这是否是内存结构。

您无需执行任何操作即可将图像存储在内存中。只需将image对象保留在字典中即可。

如果要将字典写入文件,则可能需要查看im.tostring()方法和Image.fromstring()函数

http://effbot.org/imagingbook/image.htm

im.tostring() => string

Returns a string containing pixel
data, using the standard"raw"
encoder.

Image.fromstring(mode, size, data) =>
image

Creates an image memory from pixel
data in a string, using the standard
"raw" decoder.

仅当交换文件时,"格式"(.jpeg,.png等)才在磁盘上起作用。如果您不交换文件,则格式无关紧要。