3

I have read the topic "App Engine, PIL and overlaying text".

The code below will show a broken image, how should I correct that?

class TestImg(webapp2.RequestHandler):
    def get(self):
        text_img = Image.new('RGBA', (800,600), (0, 0, 0, 0))
        draw = ImageDraw.Draw(text_img)
        draw.text((0, 0), 'HELLO TEXT', font=ImageFont.load_default())
        self.response.headers['Content-Type'] = "image/png"
        self.response.write(draw)
Community
  • 1
  • 1

2 Answers2

6

Building on what Tim Hoffman said, your class would look something like this:

import StringIO

class TestImg(webapp2.RequestHandler):
    def get(self):
        text_img = Image.new('RGBA', (800,600), (0, 0, 0, 0))
        draw = ImageDraw.Draw(text_img)
        draw.text((0, 0), 'HELLO TEXT', font=ImageFont.load_default())

        output = StringIO.StringIO()
        text_img.save(output, format="png")
        text_layer = output.getvalue()
        output.close()

        self.response.headers['Content-Type'] = 'image/png'
        self.response.write(text_layer)
Tkingovr
  • 1,295
  • 15
  • 32
2

The draw object you have can't be passed back to the browser as it is not png as such.

You need to call draw.save() and pass it a StringIO object to write the file to. (you will also need to supply a file type). You would thenself.response.write(the_stringio.getvalue())

Tim Hoffman
  • 12,908
  • 1
  • 15
  • 28