0

In some tutorials was explained to use StringIO in Pillow save method. but when I use this testcode:

from PIL import Image
from io import StringIO, BytesIO

photo = Photo.objects.get(pk=1)
bytes = BytesIO()
string = StringIO()

image = Image.open(photo.image)
image.save(string, 'PNG')

then I get the error:

string argument expected, got 'bytes'

But when I use BytesIO like this:

image.save(bytes, 'PNG')

it works fine. That is strange, because the error message says that a string is expected and bytes is wrong, but obviously the opposite is correct. And that is also contrary to the informations I got while checking tutorials.

Maybe the behavior of save() was changed in the Pillow fork, and the error message was not updated? Or is it different because I use Python 3 with io module instead of StringIO module?


edit, examples where StringIO is proposed

Asara
  • 2,791
  • 3
  • 26
  • 55
  • It is probably just a mistake in the tutorial. I don't know why would they save as image as a string with StringIO when it should be saved with BytesIO to be readable by image readers. It is meant to be used with BytesIO. – ljmocic Oct 15 '18 at 14:20
  • I was also confused about that, but my interpretation was, that `save()` expects a filepath as string and you can trick it with using presenting this StringIO object. Actually, the errormessage says that a string should be provided. There is for example this (first) answer that advises to use StringIO (but for PIL): https://stackoverflow.com/questions/3723220/how-do-you-convert-a-pil-image-to-a-django-file – Asara Oct 15 '18 at 15:29
  • I suspect that this is a just Python version issue: https://stackoverflow.com/questions/646286/python-pil-how-to-write-png-image-to-string – ljmocic Oct 15 '18 at 17:08
  • but then the error message is still wrong, or do I misunderstand it? – Asara Oct 15 '18 at 17:17

0 Answers0