how can i write a PIL image object to response

3,119 views
Skip to first unread message

hywang

unread,
Jul 1, 2009, 5:40:04 AM7/1/09
to web2py Web Framework
django do it like this:

from django.utils.httpwrappers import HttpResponse
from PIL import Image
def image(request):
image = Image.new("RGB", (800, 600))
response = HttpResponse(mimetype="image/png")
image.save(response, "PNG")
return response


in web2py, I did it with a file, first i save image to a file:
image.save("outut.png", "png")
then stream it:
return response.stream("output.png")

is there anyway like this to do it in web2py ?
thanks!

mdipierro

unread,
Jul 1, 2009, 10:00:39 AM7/1/09
to web2py Web Framework
You can do it like in django:

from PIL import Image
def image():
image = Image.new("RGB", (800, 600))
response.headers['Content-Type']="image/png"
image.save(response.body, "PNG")
return response.body.getvalue()

response.body is a StringIO

Tim Michelsen

unread,
Jul 11, 2009, 6:42:37 AM7/11/09
to web...@googlegroups.com
mdipierro:

> You can do it like in django:
>
> from PIL import Image
> def image():
> image = Image.new("RGB", (800, 600))
> response.headers['Content-Type']="image/png"
> image.save(response.body, "PNG")
> return response.body.getvalue()
>
> response.body is a StringIO

Here is a matplotlib based version:

# CONTROLLER:

def image_mat():
import sys
import matplotlib
matplotlib.use('Agg')
from pylab import plot, savefig
plot([1,2,3])
response.headers['Content-Type']="image/png"
savefig(response.body)

return response.body.getvalue()

# view

<img src="{{=URL(r=request,f='image_mat')}}"/>

=> this can be extended for interactive plotting using
* form as input
* numpy /scipy as support for the math

@Massimo
You may add this to the examples.

张峥

unread,
Jul 11, 2009, 7:38:46 AM7/11/09
to web...@googlegroups.com
@Massimo

I also need a example, matplotlib in the web2py, thanks

Tim Michelsen 写道:

mdipierro

unread,
Jul 11, 2009, 10:51:00 AM7/11/09
to web2py Web Framework
Very useful! I need this myself. Thanks

Massimo

M.C. Botha

unread,
Oct 2, 2014, 10:20:34 PM10/2/14
to web...@googlegroups.com
This does not work on appengine, there is no save method.
What is the appengine way of doing this?

Leonel Câmara

unread,
Oct 3, 2014, 7:22:31 AM10/3/14
to web...@googlegroups.com, why0...@163.com
I think Image.save is available in GAE, I don't use it but I see lots of code examples on the web using Image.save with GAE. Anyway, you can use Image.tobytes(encoder_name='PNG') and write that to response.body.
Reply all
Reply to author
Forward
0 new messages