【问题标题】:Python pymysql: How to load an image from database?Python pymysql:如何从数据库加载图像?
【发布时间】:2017-03-02 23:40:44
【问题描述】:

我想在 PyQt5 窗口中加载并显示我的数据库中的图像。 但是我的脚本不起作用。

    connection = None
    result = None

    try:
        connection = pymysql.connect(host = 'localhost',
                                     user = 'root',
                                     db = 'mydatabase',
                                     cursorclass = pymysql.cursors.DictCursor)
        try:
            with connection.cursor() as cursor:
                sql = "SELECT image FROM mydatabase"
                cursor.execute(sql)
                result = cursor.fetchall() #Get all values from the image column

                image = QImage()
                image.load(result[0]['Image']) #Load image from the first row

                label = QLabel()
                label.setPixmap(QPixmap.fromImage(image))
                self.grid.addWidget(label, 0, 0)
        finally:
            connection.close()

我应该怎么做才能显示图像?

【问题讨论】:

  • 它是否显示任何错误。你有没有看过日志。如有必要,您可以启用库的日志。
  • 不,它没有显示任何错误。日志只给了我一个看起来很奇怪的代码,例如 "b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xf2\x00\x00\x00\xef\x08\ x06\x00\x00\x00\xc8...”等等。它代表数据库中的 LONGBLOB 图像。
  • 而且我还希望将图像保存为“imagename.png”。

标签: python mysql blob pyqt5 qimage


【解决方案1】:

load 方法只接受文件路径或IODevice,而您似乎将原始图像数据作为字节传递。

试试这个吧:

image = QImage.fromData(result[0]['Image'])

要保存图像,请执行以下操作:

image.save('image.png')

【讨论】:

  • 现在我收到“libpng 警告:iCCP:已知不正确的 sRGB 配置文件”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多