Pillow: Save to StringIO doesn't work

Created on 7 Nov 2016  路  4Comments  路  Source: python-pillow/Pillow

What did you do?

I tried to save an image to a StringIO object.

What did you expect to happen?

Image should be able to be written to any file-like object. I need StringIO to be able to stream it in text-form.

What actually happened?

Pillow threw an exception:
string argument expected, got 'bytes'

What versions of Pillow and Python are you using?

Python 3.4
Pillow 3.4.2

Please include code that reproduces the issue and whenever possible, an image that demonstrates the issue. The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as plone, django, or buildout, try to replicate the issue just using Pillow.

from io import StringIO
from PIL import Image

image = Image.open("test.png")
stream = StringIO()
image.save(stream, 'PNG')

Most helpful comment

In python3 you have to use a bytesio object rather than a stringio, as bytes and strings are not cross compatible.

All 4 comments

In python3 you have to use a bytesio object rather than a stringio, as bytes and strings are not cross compatible.

It worked! A dev friendly exception would be appreciated though. I've lost tons of time with this problem...

Conclusion: the fix is as below, Thank You! @wiredfool

from io import BytesIO
from PIL import Image

image = Image.open("test.png")
stream = BytesIO()
image.save(stream, 'PNG')

In python3 you have to use a bytesio object rather than a stringio, as bytes and strings are not cross compatible.

Thanks @wiredfool.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vytisb picture vytisb  路  4Comments

SysoevDV picture SysoevDV  路  3Comments

readyready15728 picture readyready15728  路  4Comments

anonymous530 picture anonymous530  路  3Comments

mmalenta picture mmalenta  路  3Comments