通过python从MySQL数据库中检索Base64图像

时间:2018-06-29 20:57:05

标签: python mysql base64 mariadb

我将使其尽可能短。我有一个代码,可以在一天的不同时间将数据发送到数据库。发送的一种数据类型是来自热像仪的图像。这部分工作正常,并将图像编码为base64并将其以“ LONGBLOB”数据类型发送到DB。

现在,我正在编写一个脚本来从数据库中读取图像,但是我的代码正在读取编码图像字符串作为整数。

#aggregate on size which counts NA's
mydf = mydf.groupby(['date_ym','category']).agg(['size', 'count', 'mean', 'median']).reset_index()
#Renaming columns
mydf.columns = ['date_ym','category', 'countNA', 'count', 'mean', 'median']
#countNA = size - count
mydf['countNA'] = mydf['countNA'] - mydf['count']

现在读入数据并将其存储:(如果您仅读入文件,此代码将起作用!)

 #Audit to the database

with open("C:/Users/danie/Desktop/image7.png", "rb") as image:
        image_read = image.read() 
        Image =base64.b64encode(image_read) 

        sql = "INSERT INTO flirimage (Image) VALUES (%s)"
        arg=('Image')
        cursor.execute(sql % arg)
        db.commit()

运行代码时:

import MySQLdb as mariadb
import base64

db = mariadb.connect(host="127.0.0.1", user="root", passwd="SECRET", 
db="SECRET")
cursor = db.cursor()

ImageEncoded=cursor.execute("select * from flirimage")
db.commit()

image_64_decode=base64.b64decode(ImageEncoded)

filename='C:/Users/danie/Desktop/image_audit.png'
with open(filename, 'wb') as f:
    f.write(image_64_decode)

 db.close()

在我看来,将Base64字符串保存在数据库中的方式存在一些问题。但是我可能是错的。

编辑:

我想证明进入数据库的数据是直接编码的。运行第一个代码后。由于这篇文章很长,因此我没有将整个base64字符串包括在内。...

TypeError: argument should be a bytes-like object or ASCII string, not 'int'

ImageEncoded
Out[38]: 1

0 个答案:

没有答案