Serve a dynamically generated image with Django

前端 未结 4 1159
[愿得一人]
[愿得一人] 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: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')
    

提交回复
热议问题