Using PIL to paint an image in App Engine

I read the topic " App Engine, PIL and Text Overlay .

The code below will show a damaged image, how to fix it?

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) 
+3
source share
2 answers

Based on what Tim Hoffman said, your class will 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) 
+6
source

The drawing object that you have cannot be transferred back to the browser because it is not png as such.

You need to call draw.save () and pass it a StringIO object to write the file. (you will also need to specify the file type). Then you are self.response.write(the_stringio.getvalue())

+2
source

All Articles