How to return in-memory PIL image from WSGI applic

2019-06-19 16:27发布

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条回答
啃猪蹄的小仙女
2楼-- · 2019-06-19 17:26

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.

查看更多
登录 后发表回答