Python PyQt5:将图像数据存储到phpmyadmin数据库中 [英] Python PyQt5: Store image data into a phpmyadmin database

查看:1235
本文介绍了Python PyQt5:将图像数据存储到phpmyadmin数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将.png文件上传到我的数据库中。

I want to upload a .png file into my database.

    fileName = QFileDialog().getOpenFileName()
    filePath = str(fileName[0]) # Path of the image data

    self.myImage = filePath


    connection = pymysql.connect(host = 'localhost',
    user = 'root',
    db = 'mydatabase',
    cursorclass = pymysql.cursors.DictCursor)  
    cur = connection.cursor()

    cur.execute("INSERT INTO mytable VALUES('" + self.myImage + "')")  
    connection.commit()

但是有些事情是错误的,因为如果我查看我的本地数据库,图像将保存为二进制文件,我无法打开或下载它。
如何正确地将图像上传到我的数据库?

But something is wrong, because if I look in my local database the image is saved as binary file and I can't open or download it. What can I do to upload an image into my database properly?

推荐答案

您只需要阅读图像文件并将数据作为blob存储在数据库中:

You just need to read the image file and store the data as a blob in the database:

with open(filePath, 'rb') as stream:
    blob = stream.read()
    cur.execute("INSERT INTO mytable VALUES(%s)", [blob])

要将blob转换为像素图:

To convert the blob into a pixmap:

pixmap = QtGui.QPixmap()
pixmap.loadFromData(blob)

这篇关于Python PyQt5:将图像数据存储到phpmyadmin数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆