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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use the
BytesIOclass to get a wrapper around strings that behaves like a file. TheBytesIOobject provides the same interface as a file, but saves the contents just in memory:You have to explicitly specify the output format with the
formatparameter, otherwise PIL will raise an error when trying to automatically detect it.If you loaded the image from a file it has a
formatproperty that contains the original file format, so in this case you can useformat=image.format.In old Python 2 versions before introduction of the
iomodule you would have used theStringIOmodule instead.