Django使用HttpResponse返回图片并显示的方法

做了一个关于Django的小案例,想要在网页中显示图片,直接在img标签的src属性写图片的路径是不能显示的,查询资料发现在Django中使用图片这类的资源相当繁琐需要进行一定D的配置,摸索了一会没有整明白,想到了写Java时使用文件流返回图片,于是想到使用该种方式来显示图片。

使用实例如下:

views.py

def my_image(request,news_id): 
  d = path.dirname(__file__) 
  #parent_path = path.dirname(d) 
  print("d="+str(d)) 
  imagepath = path.join(d,"static/show/wordimage/"+str(news_id)+".png") 
  print("imagepath="+str(imagepath)) 
  image_data = open(imagepath,"rb").read() 
  return HttpResponse(image_data,content_type="image/png") #注意旧版的资料使用mimetype,现在已经改为content_type 

urls.py

urlpatterns = [ 
  url(r'^index/$', views.index,name="index"), 
  url(r'^search/$', views.search,name="search"), 
  url(r'^science/(?P<news_id>.+)/$', views.science,name="science"), 
  <strong>url(r'^image/(?P<news_id>.+)/$',views.my_image,name="image"),</strong> 
] 

temlate:

<img src="{% url 'show:image' param.id %}" alt="{{param.id}}"/> 

以上这篇Django使用HttpResponse返回图片并显示的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。