Python PIL:如何将PNG图像写入字符串 [英] Python PIL: how to write PNG image to string

查看:229
本文介绍了Python 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.

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

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