python将图片转为base64编码并在前端页面显示

1. 将图片转化为base64编码

import base64

with open("C:/1.jpg", "rb") as f:
    # b64encode是编码,b64decode是解码
    base64_data = base64.b64encode(f.read())
    # base64.b64decode(base64data)
    base64_data_str = str(base64_data, encoding="utf-8")
    html_str = "data:image/jpg;base64," + base64_data_str
print(base64_data_str)

2. 在html网页显示

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <img src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEASABI ...... F//9k=" />
body>
html>

3. 后端传base64到前端展示

在实际应用中,前端有时不能直接加载本地图片路径,所以需要把图片转为base64格式后,再传到前端进行展示:

后端代码:

import base64
from django.shortcuts import render
from django.core.paginator import Paginator


def recog(request, image_file_list):
    img_list = []
    for image in image_file_list:
        with open(image, "rb") as f:
            # b64encode是编码,b64decode是解码
            base64_data = base64.b64encode(f.read())
            # base64.b64decode(base64data)
            base64_data_str = "data:image/jpg;base64," + str(base64_data, encoding="utf-8")
            img_list.append(base64_data_str)

    paginator = Paginator(img_list, 1)  # 实例化Paginator, 每页显示1条数据
    page = paginator.page(paginator.num_pages)  # 传递当前页的实例对象到前端
    # print(page.paginator, page.object_list)
    context = {"page": page}

    return render(request, 'recog.html', context)

前端代码(部分):

{% for item in page %}
    <div>
        <img src="{{ item }}" />
    div>
{% endfor %}

你可能感兴趣的:(django,python,django,前端)