服务与Django的一个动态生成图像 [英] Serve a dynamically generated image with Django

查看:330
本文介绍了服务与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图像库)。你需要替换你的最后一行(例如,如果你想成为一个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

请参阅这里了解更多信息。

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

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