我已阅读“App Engine, PIL and overlaying text”主题。
下面的代码会显示一张损坏的图片,我该如何更正呢?
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)
答案 0 :(得分:6)
根据蒂姆霍夫曼的说法,你的班级看起来像这样:
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)
答案 1 :(得分:2)
您拥有的绘图对象无法传递回浏览器,因为它不是png。
您需要调用draw.save()并将其传递给StringIO对象以将文件写入。 (您还需要提供文件类型)。然后你会self.response.write(the_stringio.getvalue())