Fix Python – How to write PNG image to string with the PIL?


Asked By – maxp

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

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

Now we will see solution for issue: How to write PNG image to string with the PIL?


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:, format="GIF")
    contents = output.getvalue()

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

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

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

This question is answered By – sth

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0