【问题标题】:edit image header display image object to django template编辑图像标题显示图像对象到 django 模板
【发布时间】:2014-09-18 08:45:05
【问题描述】:

我已使用以下代码将图像转换为 base64 字符串。基于此字符串,想要创建 Image 对象并希望向其添加一些标头,例如,

到期:2013 年 4 月 29 日星期一 21:44:55 GMT Cache-Control: max-age=0, no-cache, no-store ,

并将该对象作为图像打印到 django 模板。

在 django 中可以吗?

这是将img从url转换为base64的代码。

import mimetypes
import urllib2
def stringifyImage(url):
    tmpdir = 'tmp'
    mmtp = mimetypes.guess_type(url, strict=True)
    if not mmtp[0]:
        return False

    ext = mimetypes.guess_extension(mmtp[0])
    f = open(tmpdir+'tmp'+ext,'wb')
    f.write(urllib2.urlopen(url).read())
    f.close()
    img = open(tmpdir+'tmp'+ext, "rb").read().encode("base64").replace("\n","")
    return img

【问题讨论】:

  • 所以当你说将图像对象添加到 Django 时,“只是澄清一下”,你还想显示你改变了标题的图像吗?
  • @LearningNeverStops 是的
  • 猜测:所以您仍然可以取回图像对象并通过上下文将其传递给httpresponse,然后可以通过模板访问该对象对吗?您是否尝试过为 html 的 src 属性访问相同的属性?
  • 那么你让 HttpResonse 工作了吗? :)

标签: python django image python-imaging-library


【解决方案1】:

看到你的问题我明白了:

  1. 您有想要将其传递给 Django 模板的图像
  2. 设置过期、无缓存相关标头

我觉得你可以通过将图像对象作为 HttpResponse 发送,然后为你正在寻找的标题添加装饰器来实现它。

您可以查看以下链接:

  1. A decorator that adds additional headers to disable caching
  2. A decorator that helps for adding expiry date
  3. 然后,一旦您设置了所需的标头,您就可以为 tempate 请求的图像发​​送 HttpResponse:

views.py 内部

from PIL import Image
from django.views.decorators.cache import cache_page

@cache_page(60 * 15)    #cached for 15 minutes
def getImg(request):
    #Getting the image url

    #image is the Image object of PIL

    # serialize to HTTP response http://effbot.org/zone/django-pil.htm
    response = HttpResponse(mimetype="image/png")
    image.save(response, "PNG")
    return response
  1. 然后在你的 img 标签中,使用 src 的模板(考虑到 url.py 有视图标识符):

    <img src='{% url getImg %}' >

进一步阅读:Django's Cache Framework

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 2016-12-13
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多