【计算机网络基础——系列13】python操作数据库储存图片,取出图片放到前端页面展示

系列文章目录

【计算机网络基础——系列1】-matlab与python使用socket udp进行进程间通信
【计算机网络基础——系列2】-matlab与python使用socket tcp进行进程间通信
【计算机网络基础——系列3】输入url后页面会遇到的问题
【计算机网络基础——系列4】关于HTTP请求的相关内容
【计算机网络基础——系列5】前端遇到的三种网络攻击
【计算机网络基础——系列6】浏览器缓存之cookie、session、localstorage
【计算机网络基础——系列7】浏览器缓存之—http缓存
【计算机网络基础——系列8】前端优化总结
【计算机网络基础——系列9】restful规范;dns劫持
【计算机网络基础——系列10】osi网络结构;tcp协议保持传输的可靠性;SSL
【计算机网络基础——系列11】实现python作为服务端与qt进行udp通信
【计算机网络基础——系列12】flask作为服务器与vue实现websocket通信
【计算机网络基础——系列13】python操作数据库储存图片,取出图片放到前端页面展示



前言

竞赛要求,要使用angular.js实现app,其中有一个功能是实现图片存入数据库,并能在app中展示。


提示:以下是本篇文章正文内容,下面案例可供参考

一、python中对图片的格式操作

1.1 引入模块

import json
from flask import Flask, jsonify, request  # 引入核心处理模块
from flask_cors import CORS
import base64
import time
import pymysql

1.2 引入图片,转换为base64格式

  1. 'rb’加上才能将图片读取为二进制
  2. fin.read()将图片数据转换为二进制数据放入到img中
  3. base64.b64encode(img)将二进制格式转换为base64格式
fin = open("./222.jpg",'rb')   #'rb'加上才能将图片读取为二进制
img = fin.read()#将二进制数据读取到img中
img_stream = base64.b64encode(img)
print('picture',img_stream)
print('picturetype',type(img_stream))
fin.close()

1.3 将从数据库中取出的图片格式转换为json传送到前端

  • database.get_image( “id =”" + ‘2’ + “”")是前面的数据库取出图片函数,返回值为二进制流的格式;
  • base64.b64encode将二进制流转换为base64格式;
  • s = img_stream.decode()对其进行解码,便于传输;
  • jsonify({‘ok’: s})以jsonify格式传递到前端;
img_stream = base64.b64encode(database.get_image( "id =\"" + '2' + "\""))
s = img_stream.decode()
return jsonify({'ok': s})  # 返回JSON格式的数据

二、python中对图片进行数据库操作

2.1 连接数据库

类名为Database

class Database():
    def __init__(self):
        self.connection = pymysql.connect(host="127.0.0.1",user= "root", password="123456",database= "wk",charset='utf8',use_unicode=True)
        self.cursor = self.connection.cursor()

2.2 创建数据表

  • tablename为创建的数据表的名字;
  • 数据表创建了三个表头,id为储存图片的名字,data为储存的日期,image为存储的图片(格式是blob格式);
  • self.cursor.execute(sql)开始创建
    def create_slx(self,tablename):  # 创建表格
        print("创建表tablename:" + tablename)
        sql = """
            CREATE TABLE IF NOT EXISTS %s(
           
            id        VARCHAR(255)     NOT NULL,
            data    VARCHAR(255)     NOT NULL,
            image           longblob
            
            )CHARACTER SET utf8 COLLATE utf8_general_ci
            """ % (tablename)
        self.cursor.execute(sql)
        print('创建表格结束')

2.3 插入图片

    def insert_image(self, id,datas,image):
            sql = "insert into picture(id,datas,image) values(%s,%s,%s)"
            imagee=(id,datas,image)
            self.cursor.execute(sql, imagee)
            self.connection.commit()

如下所示:
在这里插入图片描述


2.4 从数据库中取出图片

  • where_condition是查找图片的索引,一般用id序号查找;
  • image = self.cursor.fetchone()[2]查找第三列的图片;
  • file.write(image)将图片取出后存入本地文件中,path为保存路径;
  • return image为返回的二进制流数据格式,便于后续将其返回至前端;
    def get_image(self,path,where_condition):
        sql ="""select * from picture where %s""" % (where_condition)
        self.cursor.execute(sql)
        image = self.cursor.fetchone()[2]
        print('sucess111',image)
             with open(path, "wb") as file:
              file.write(image)
             except pymysql.Error:
              print(pymysql.Error)
             except IOError:
              print(IOError)
       		 return image

三、python flask与前端进行数据交互

3.1 python端实现

  • 接口就是login;
  • 以下为对数据库进行操作;

database = Database()
database.create_slx(“picture”)
database.insert_image(2, 626, img)
database.get_image( “id =”" + ‘2’ + “”")

  • s = img_stream.decode()对其进行解码,便于传输;
  • jsonify({‘ok’: s})以jsonify格式传递到前端;
@app.route('/login', methods=['POST'])  # 登录
def login():
    database = Database()
    database.create_slx("picture")
    database.insert_image(2, 626, img)
    database.get_image( "id =\"" + '2' + "\"")
    print("进入登陆查询")
    req = request.get_json()
    print(req)

    img_stream = base64.b64encode(database.get_image( "id =\"" + '2' + "\""))
    s = img_stream.decode()
    return jsonify({'ok': s})  # 返回JSON格式的数据

3.2 前端实现

  • 使用了基于jquery的ajax实现http通信,将获取到的图片内容转存到dat中,然后再操作dom,在视图中显示出图片;picture.src= 'data:image/png;base64,' + dat实现将图片以base64格式挂载上视图。

.ts

	 var dict=1
     var dat
    $.ajax({
      type: "POST",
      url: "http://localhost:5000/login",
      contentType: 'application/json; charset=UTF-8',
      data: JSON.stringify(dict) ,
      dataType: "json",
      success: function(res) {
         dat=res['ok'];
        var picture = document.createElement('img'); // 创建一个img元素
        // 该img元素将会成为 id 为 pictureLocation 的 div 的孩子,需获取这个元素
        var d1 = document.getElementById('pictureLocation'); 
        // 设置这个img元素的一些属性
        // img元素的 src 尤为重要:
        // img.ok中存储的是图片的base64,且图片原先的格式是png;在 src 中均有体现
        picture.src = 'data:image/png;base64,' + dat;
        picture.alt = "";
        picture.width = 100;
        picture.height = 100;
        d1.appendChild(picture);
        console.log('rec',dat)
      },
      error: function(xhr, type) {
      }
    });

.html

 <div id="pictureLocation">
		picture
  </div>

四、出现的各类问题

4.1 python中中出现的

4.1.1 关键字冲突

check the manual that corresponds to your MySQL server version for the right syntax
  • 原因:数据库表字段与SQL关键字冲突导致的错误修改;
  • 解决:数据库表中冲突字段名称,修改为和 SQL语句关键字不冲突的其他名称。

4.1.2 函数参数数量冲突

takes 1 positional argument but 2 were given
  • 原因:发现调用类文件的def中,少了个参数self: def insert_image(self, id,datas,image):
  • 解决:加上self即可;

4.1.3 编码格式设置冲突

AttributeError: 'NoneType' object has no attribute 'encode'
  • 原因:charset编码格式设置错误
  • 原因:charset编码格式设置错误

4.1.4 插入数据库时的参数设置冲突

Column count doesn‘t match value count at row 1 
  • 原因:insert into user(colum1,colum2,colum3),而数据库中对应的表格只有两列
  • 解决:插入参数数量与表格中数量一致即可。

五、base64 转码测试网站

这个网站可以实现base64转图片,也可图片转base64,还有其他各种格式的相互转换,便于测试base64的格式正确。
在这里插入图片描述

网址:点击即可进入


码字不易~, 各位看官要是看爽了,可不可以三连走一波,点赞皆有好运!,不点赞也有哈哈哈~~~

  • 7
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

让子弹飞一会儿=>

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值