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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1074200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:25:18  来源:igfitidea点击:

Serve a dynamically generated image with Django

pythonajaxdjangoimage

提问by pufferfish

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,并添加某种缓存机制,但我的理解是这不会影响解决方案的这一部分。

回答by Vinay Sajip

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):

我假设您正在使用 PIL(Python 成像库)。您需要将最后一行替换为(例如,如果您想提供 PNG 图像):

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

See herefor more information.

请参阅此处了解更多信息。

回答by geowa4

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 比较陌生。我没能在 Django 本身中找到任何东西,但我偶然发现了一个关于 Google Code 的项目,它可能对你有帮助:

django-dynamic-media-serve

django-dynamic-media-serve

回答by tolazytosignup

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