Serve a dynamically generated image with Django

前端 未结 4 1137
[愿得一人]
[愿得一人] 2020-12-01 04:03

How do I serve a dynamically generated image in Django?

I have an html tag


...
    
...
&         


        
相关标签:
4条回答
  • 2020-12-01 04:12

    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
    
    0 讨论(0)
  • 2020-12-01 04:15

    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.

    0 讨论(0)
  • 2020-12-01 04:17

    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')
    
    0 讨论(0)
  • 2020-12-01 04:34

    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

    0 讨论(0)
提交回复
热议问题