【问题标题】:Truncated image displayed when tried to retrieve from mysql database using python尝试使用 python 从 mysql 数据库中检索时显示截断的图像
【发布时间】:2021-08-12 05:34:02
【问题描述】:

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

我可以将它作为 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()

感谢任何帮助。

【问题讨论】:

    标签: python mysql tkinter python-imaging-library


    【解决方案1】:

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

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

    MySQL docs on the BLOB and TEXT types 声明:

    如果未启用严格 SQL 模式,并且您为 BLOB 或 TEXT 列分配的值超过了列的最大长度,则该值将被截断以适应并生成警告。

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

    我用一些小图像运行了您的代码,它运行良好:显示的图像没有截断。

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

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多