尝试使用 python 从 mysql 数据库检索时显示的截断图像

Truncated image displayed when tried to retrieve from mysql database using python

我正在尝试从我的 sql 数据库中插入和检索图像作为 BLOB 数据。

我可以将其作为 BLOB 插入。但是,当我尝试检索它时,检索到的图像被截断了。

首先它显示OSError: image file is truncated。通过参考一些帖子,我包含了代码 ImageFile.LOAD_TRUNCATED_IMAGES = True。现在没有错误了。

但是图片还是被截断了。

这是我的代码。

from tkinter import *
from PIL import ImageTk,Image
from tkinter import filedialog
import mysql.connector
import io
from PIL import ImageFile

root = Tk()

browse_button = Button(root,text ='Browse',command = lambda:open_file())
browse_button.pack()

display_button = Button(root,text ='display',command =lambda:display_file())
display_button.pack()

def display_file():
    ImageFile.LOAD_TRUNCATED_IMAGES = True
    person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
    cursor_variable = person.cursor()
    sql = "SELECT data FROM image_db WHERE id = 5"
    cursor_variable.execute(sql)
    all_data = cursor_variable.fetchall()
    image = all_data[0][0]
    image = Image.open(io.BytesIO(image))
    image.show()
    person.commit()
    person.close()


def open_file():
    root.filename = filedialog.askopenfilename(initialdir="/Users/write/PycharmProjects/slider/img", title='Select a File',
                                               filetypes=(('png files', '*.png'), ('jpeg files', '*.jpeg'),
                                                          ('jpg files', '*.jpg')))
    my_label = Label(root, text=root.filename).pack()
    my_image = ImageTk.PhotoImage(Image.open(root.filename))
    path = root.filename
    id = '5'


    person = mysql.connector.connect(host="localhost", user="root", password="", database="image")
    cursor_variable = person.cursor()
    thedata = open(root.filename, 'rb').read()
    sql = "INSERT INTO image_db (id,data) VALUES ('" + id + "',%s)"
    cursor_variable.execute(sql, (thedata,))
    person.commit()
    person.close()


root.mainloop()

感谢任何帮助。

我将根据您的问题中未指定(或至少未明确指定)的一些假设来猜测您的问题:

  1. 您的 image_db table 的 data 列的类型为 BLOB,而不是 MEDIUMBLOBLONGBLOB
  2. 您尝试上传的图片大于 64KB。
  3. 你不是 运行 严格 SQL 模式下的数据库。

MySQL docs on the BLOB and TEXT types 指出:

If strict SQL mode is not enabled and you assign a value to a BLOB or TEXT column that exceeds the column's maximum length, the value is truncated to fit and a warning is generated.

根据 this answerBLOB 列的最大长度为 64KB。因此,将所有假设结合在一起为我们提供了一种可能的解释来解释您所看到的行为。

我 运行 你的代码有一些小图片并且工作正常:显示的图片没有被截断。

我建议将 image_db table 的 data 列更改为 MEDIUMBLOBLONGBLOB,具体取决于您需要的图像大小存储在您的数据库中。