python 將圖片轉換為base64編碼轉儲進數據庫
阿新 • • 發佈:2018-08-30
join 圖片轉換 exce 中間 sof com sys hal ims
# _*_ coding: utf-8 _*_
#中間件:拓展工具遍歷文件夾,對文件夾圖片進行base64編碼,寫入數據庫,並且讀取查找方法
__author__ = ‘wf15038‘
__date__ = "2018/8/28 18:38"
import pymysql
import sys
from datetime import datetime
import base64
import os
now = datetime.now().strftime(‘%Y-%m-%d %H:%M:%S‘)
def dbinfo():
conn = ""
conn = pymysql.connect(host=‘ip地址‘, port=3505, user="數據庫", password=‘密碼‘, database=‘itportal‘,
charset=‘utf8‘,cursorclass =pymysql.cursors.DictCursor)
cur = conn.cursor()
if not cur:
return "access db is fail!"
else:
return conn
local_dir = ‘E:\\xiugai\\ico‘
try:
for root,dirs,files in os.walk(local_dir):
for filepath in files:
image_path = os.path.join(local_dir,filepath)
imagename,_ = os.path.splitext(filepath)
print(imagename)
fp = open(image_path,‘rb‘)
base64_date = base64.b64encode(fp.read())
fp.close()
try:
conn=dbinfo()
conncur = conn.cursor()
sql_insertimage="insert into soft_PT (softname,imstore,submittime) VALUE (%s, %s, %s) "
conncur.execute(sql_insertimage, (imagename,base64_date,now))
seatdic= conncur.fetchall()
conn.commit()
conn.close()
except pymysql.Error as e :
print("Error %d %s" % (e.args[0],e.args[1]))
sys.exit(1)
except IOError as e:
print("Error %d %s" % (e.args[0],e.args[1]))
sys.exit(1)
try:
conn = dbinfo()
conncur = conn.cursor()
sql_selectimage = "select imstore from soft_PT"
conncur.execute(sql_selectimage)
softpath = conncur.fetchall()
softpathlist = [x[‘imstore‘].decode(‘gbk‘) for x in softpath]
print(softpathlist)
for i in softpathlist:
print(i)
conn.commit()
conn.close()
except pymysql.Error as e :
print(e)
sys.exit(1)
python 將圖片轉換為base64編碼轉儲進數據庫