How to return a PIL image in memory from a WSGI application

I read a lot of posts, such as this one , which details how to dynamically return an image using WSGI. However, all the examples that I saw open the image in binary format, reading it and then returning this data (this works fine for me).

I'm stuck trying to achieve the same thing using a PIL image object in memory. I do not want to save the image to a file, since I already have the image in memory.

Considering this:

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

I 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 for the client. But I will get an error for the image, saying that something is wrong with the returned image.

What other methods exist?

+6
source share
1 answer

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

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

You will need to check which values ​​you can use for the format.

+11
source

Source: https://habr.com/ru/post/905651/


All Articles