简体   繁体   English

使用 Django 提供动态生成的图像

[英]Serve a dynamically generated image with Django

How do I serve a dynamically generated image in Django?如何在 Django 中提供动态生成的图像?

I have an html tag我有一个 html 标签

<html>
...
    <img src="images/dynamic_chart.png" />
...
</html>

linked up to this request handler, which creates an in-memory image链接到这个请求处理程序,它创建一个内存中的图像

def chart(request):
    img = Image.new("RGB", (300,300), "#FFFFFF")
    data = [(i,randint(100,200)) for i in range(0,300,10)]
    draw = ImageDraw.Draw(img)
    draw.polygon(data, fill="#000000")
    # now what?
    return HttpResponse(output)

I also plan to change the requests to AJAX, and add some sort of caching mechanism, but my understanding is that wouldn't affect this part of the solution.我还计划将请求更改为 AJAX,并添加某种缓存机制,但我的理解是这不会影响解决方案的这一部分。

I assume you're using PIL (Python Imaging Library).我假设您正在使用 PIL(Python 成像库)。 You need to replace your last line with (for example, if you want to serve a PNG image):您需要将最后一行替换为(例如,如果您想提供 PNG 图像):

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

See here for more information.请参阅此处了解更多信息。

I'm relatively new to Django myself.我自己对 Django 比较陌生。 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 中找到任何东西,但我偶然发现了一个关于 Google Code 的项目,它可能对你有帮助:

django-dynamic-media-serve django-dynamic-media-serve

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

Another way is to use BytesIO.另一种方法是使用 BytesIO。 BytesIO is like a buffer. BytesIO 就像一个缓冲区。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM