How to return in-memory PIL image from WSGI application

旧城冷巷雨未停 提交于 2019-12-08 20:24:31

问题


I've read a lot of posts like this one that detail how to dynamically return an image using WSGI. However, all the examples I've seen are opening an image in binary format, reading it and then returning that data (this works for me fine).

I'm stuck trying to achieve the same thing using an in-memory PIL image object. I don't want to save the image to a file since I already have an image in-memory.

Given this:

fd = open( aPath2Png, 'rb')
base = Image.open(fd)
... lots more image processing on base happens ...

I've tried this:

data = base.tostring()
response_headers = [('Content-type', 'image/png'), ('Content-length', len(data))]
start_response(status, response_headers)
return [data]

WSGI will return this to the client fine. But I will receive an error for the image saying there was something wrong with the image returned.

What other ways are there?


回答1:


See Image.save(). It can take a file object in which case you can write it to a StringIO instance. Thus something like:

output = StringIO.StringIO()
base.save(output, format='PNG')
return [output.getvalue()]

You will need to check what values you can use for format.



来源:https://stackoverflow.com/questions/8809130/how-to-return-in-memory-pil-image-from-wsgi-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!