Python实现将图片以二进制格式保存到MySQL数据库中,以及取出:

创建数据库表格式:

CREATE TABLE photo ( photo_no int(6) unsigned NOT NULL auto_increment, image MEDIUMBLOB, PRIMARY KEY (`photo_no`) );

Python实现将图片以二进制格式保存到MySQL数据库中:

import sys
import pymysql
from PIL import Image
import os
 
path = "./"

fp = open("./1.png", 'rb')
img = fp.read()
fp.close()

database = pymysql.connect(host="localhost", user="root", passwd="", db="hua")
cursor = database.cursor()
sql = "INSERT INTO photo (image) VALUES  (%s);"
args = (img)
cursor.execute(sql, args)
database.commit()
cursor.close()
database.close()

print("============")
print("Done! ")

Python实现从MySQL数据库中将二进制格式的图片保存到本地:

import pymysql as mdb
import sys

conn = mdb.connect(host='localhost',user='root',passwd='',db='hua')
cursor = conn.cursor()
cursor.execute("SELECT image FROM photo LIMIT 1")
fout = open('quchu1.png','wb')
fout.write(cursor.fetchone()[0])
fout.close()
cursor.close()
conn.close()
posted @ 2019-11-15 22:01  小大大小  阅读(5058)  评论(0编辑  收藏  举报