编辑图像标题显示图像对象到django模板

时间:2014-09-18 08:45:05

标签: python django image python-imaging-library

我已使用以下代码将图像转换为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

1 个答案:

答案 0 :(得分:0)

看到你的问题,我看到了:

  1. 您要将图像传递给Django模板
  2. 设置过期,无缓存相关标头
  3. 我觉得你可以通过将图像对象作为HttpResponse发送,然后为你要查找的标题添加装饰器来实现它。

    您可以查看以下链接:

    1. A decorator that adds additional headers to disable caching
    2. A decorator that helps for adding expiry date
    3. 然后,一旦设置了所需的标题,就可以为tempate请求的图像发​​送HttpResponse:
    4. 在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 %}' >

      2. 进一步阅读:Django's Cache Framework