我已使用以下代码将图像转换为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
答案 0 :(得分:0)
看到你的问题,我看到了:
我觉得你可以通过将图像对象作为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
然后在你的img标签中,使用src的模板(考虑到url.py有视图标识符):
<img src='{% url getImg %}' >
进一步阅读:Django's Cache Framework