[Django]-Serve a dynamically generated image with Django

31๐Ÿ‘

โœ…

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

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

See here for more information.

๐Ÿ‘คVinay Sajip

3๐Ÿ‘

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

django-dynamic-media-serve

๐Ÿ‘คgeowa4

3๐Ÿ‘

I was looking for a solution of the same problem

And for me this simple approach worked fine:

from django.http import FileResponse

def dyn_view(request):

    response = FileResponse(open("image.png","rb"))
    return response
๐Ÿ‘คtolazytosignup

1๐Ÿ‘

Another way is to use BytesIO. BytesIO is like a buffer. So one can save the image (which is fast enough than writing to disk) in 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')
๐Ÿ‘คJayanta

Leave a comment