如何使用PIL将PNG图像写入字符串? [英] How to write PNG image to string with the PIL?

查看:50
本文介绍了如何使用PIL将PNG图像写入字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have generated an image using PIL. How can I save it to a string in memory? The Image.save() method requires a file.

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

I'd like to have several such images stored in dictionary.

推荐答案

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

You can use the BytesIO class to get a wrapper around strings that behaves like a file. The BytesIO object provides the same interface as a file, but saves the contents just in memory:

import io

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

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

You have to explicitly specify the output format with the format parameter, otherwise PIL will raise an error when trying to automatically detect it.

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

If you loaded the image from a file it has a format parameter that contains the original file format, so in this case you can use format=image.format.

在引入 io 模块之前的旧 Python 2 版本中,您将使用 StringIO 模块.

In old Python 2 versions before introduction of the io module you would have used the StringIO module instead.

这篇关于如何使用PIL将PNG图像写入字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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