Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return in-memory PIL image from WSGI application

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?

like image 255
angeloHarpy Avatar asked Jan 10 '12 19:01

angeloHarpy


People also ask

What does image getdata return?

getdata() Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

How do I save a PIL library image?

Saving an image can be achieved by using . save() method with PIL library's Image module in Python.

How do I send PIL?

Steps to be taken for filing a Writ Petition / PIL: Approach a public interest lawyer or organization to file the case. Collect necessary documents such as title deeds, proof of residence, identity proof, notice, resettlement policy if any, and photographs of the eviction.


1 Answers

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.

like image 82
Graham Dumpleton Avatar answered Sep 19 '22 19:09

Graham Dumpleton