[ACCEPTED]-Serve a dynamically generated image with Django-image

Accepted answer
Score: 31

I assume you're using PIL (Python Imaging 3 Library). You need to replace your last 2 line with (for example, if you want to serve 1 a PNG image):

response = HttpResponse(mimetype="image/png")
img.save(response, "PNG")
return response

See here for more information.

Score: 3

I'm relatively new to Django myself. I haven't 3 been able to find anything in Django itself, but 2 I have stumbled upon a project on Google 1 Code that may be of some help to you:

django-dynamic-media-serve

Score: 2

I was looking for a solution of the same 2 problem

And for me this simple approach 1 worked fine:

from django.http import FileResponse

def dyn_view(request):

    response = FileResponse(open("image.png","rb"))
    return response
Score: 1

Another way is to use BytesIO. BytesIO is 3 like a buffer. So one can save the image 2 (which is fast enough than writing to disk) in 1 that buffer.

from PIL import Image, ImageDraw
import io

def chart(request):
    img = Image.new('RGB', (240, 240), color=(250,160,170))
    draw = ImageDraw.Draw(img)
    draw.text((20, 40), 'some_text')

    buff = io.BytesIO()
    img.save(buff, 'jpeg')
    return HttpResponse(buff.getvalue(), content_type='image/jpeg')

More Related questions