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).