0

I am trying to turn a text field into an image using pillow and Django.

The text is created dynamically (so I cannot create all text beforehand, turn it into images, and upload them). Each image has to be created "on the fly" and then displayed on the correct page.

I understand (maybe?) that the correct way to do that is to use the IO package to load the picture into memory and then pass it on to the django html to be displayed there. But I am having trouble with the execution.

I am quite new to Django / Python programming, so I got someone to help me who told me to do something like this:

def render(txt, fontsize=20, encoding=None):
   txt = txt.strip()
   lines = len(txt.splitlines()) or 1

   font = ImageFont.truetype(ARIAL_TTF, fontsize)
   width, height = font.getsize(txt)

   image = Image.new("RGBA", (width, height*lines), (232,232,232))
   draw = ImageDraw.Draw(image)

   draw.text((0, 0), txt, (0, 0, 0), font=font)

   temp = six.StringIO()
   image.save(temp, 'png')
   if encoding:
        return temp.encode(encoding)
   return temp.getvalue()

The problem is that StringIO() produces a StringIO object that cannot be read as a file(name) by image.save -- at least this is the error message I got: "expected String got Bytes". Apparently, the above runs in Python2 but that is no option for me right now (other dependencies that only work with Python3).

I tried circumventing this by using:

image.save(temp.getvalue(),'png')

But then it tells me that the file "" does not exist (which makes sense, I guess).

Jonas
  • 1
  • 1
  • 1
    Instead of using `StringIO` use [`BytesIO`](https://docs.python.org/2/library/io.html#io.BytesIO). Import it like this: `from io import BytesIO` – nik_m Mar 18 '17 at 18:33
  • I wrote an answer on a similar question a while ago here: http://stackoverflow.com/a/22742697/1925257. Ignore the HTML portion. The *"views"* code might help. – xyres Mar 18 '17 at 19:00
  • Your answer got me to the solution! Thanks a lot! (Only mini bug in yours was that I had to use BytesIO and "rewind" rather than StringIO in Python3) – Jonas Mar 18 '17 at 22:04

0 Answers0