使用Django提供动态生成的图像 [英] Serve a dynamically generated image with Django

查看:127
本文介绍了使用Django提供动态生成的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Django中提供动态生成的图像?

How do I serve a dynamically generated image in Django?

我有一个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)

我还打算将请求更改为AJAX,并添加某种缓存机制,但我的理解是不会影响这部分解决方案。

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.

推荐答案

我假设你'重新使用PIL(Python Imaging Library)。您需要更换最后一行(例如,如果要提供PNG图像):

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.

这篇关于使用Django提供动态生成的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆