django2 显示图片 输出图片

使用笨办法,指向图片的路径,然后输出图片。

首先路由设置:

# 查看图片
path('tu/', ShowTuView.as_view(), name='image')

视图代码:

import os

class ShowTuView(View):
    def get(self, request):
        num = request.GET.get('num', '')
        base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        d = base_dir
        imagepath = os.path.join(d, "media/images/" + str(num) + ".jpg")
        image_data = open(imagepath, "rb").read()
        return HttpResponse(image_data, content_type="image/jpg")

把图片放置到 media/image/1.jpg 里面

 

直接输入链接显示图片:

或者在模板中输入代码显示图片:

<img src="/tu/?num=1" alt=""/>

img标签中没有设置图片的大小,所以显示的比例是1:1。

猜你喜欢

转载自www.cnblogs.com/andu99/p/9068874.html