0

I have saved an image in mysql and I want to show it but an error occurred and I would like you to help me know where the error originates from.

def convertToBinaryData(self,filename):
    #convert digital data to bynary format
    with open(filename,'rb') as file:
        binaryData = file.read()
    return binaryData

def upload image (self):
    self.btn_Frame.filename = filedialog.askopenfilename(initialdir="C:/Users/dimitri/Pictures",title="seleccione el dibujo",filetypes=[("PNG files","*.png"),("JPG files","*.jpg")])

    self.my_image = Image.open(self.btn_Frame.filename)

    self.blobImage = self.convertToBinaryData(self.btn_Frame.filename)

    self.resize_image = self.my_image.resize((200,200),Image.ANTIALIAS)

    self.new_image = ImageTk.PhotoImage(self.resize_image)

    foto= Label(self.Predecir_Frame,image=self.new_image)
    foto.photo = self.new_image
    foto.grid(row=1,column=0,pady=10,padx=30,sticky=W)

def save_DB(self):
    if self.name_var.get()=="" or self.lastName_var.get()==""  
            messagebox.showerror("Error", "All fields are required !!!")
    else:   
        con = pymysql.connect(host="localhost", user="root",password="", database="postulantebd")
        cur = con.cursor()
        cur.execute("insert into postulantes values(%s, %s, %s, %s)",(
            self.name_var.get(),
            self.lastName_var.get(),
            self.txt_address.get('1.0', 'end-1c'),
            self.blobImage
            ))
            con.commit()
            self.v2()
            self.fetch_all()
            con.close()


def fetch_all(self):
    con = pymysql.connect(host="localhost", user="root",password="", database="postulantebd")
    cur = con.cursor()
    cur.execute("select * from postulantes")
    rows=cur.fetchall()

    if len(rows)!=0:
        self.tabla_postulante.delete(*self.tabla_postulante.get_children())
        for row in rows:
            self.tabla_postulante.insert('',END,values=row)
            con.commit()
    con.close()
        
def get_cursor(self,ev):
    cursor_row=self.tabla_postulante.focus()
    contents=self.tabla_postulante.item(cursor_row)
    row=contents['values']
    self.name_var.set(row[0]),
    self.lastName_var.set(row[1]),
    self.txt_address.delete('1.0', 'end-1c')
    self.txt_address.insert('end-1c',row[2]),
    self.blobImagen = row[3]
    readBlob=Image.open(io.BytesIO(self.blobImage))
    pic = ImageTk.PhotoImage(readBlob)
    foto = Label(self.Predecir_Frame,image=pic)
    foto.grid(row=1,column=0,pady=10,padx=30,sticky=W)

the error that appears is the following: in get_cursor readBlob=Image.open(io.BytesIO(self.blobImagen)) TypeError: a bytes-like object is required, not 'str'

I know it's long but I didn't know how to make a shorter example thanks for taking the time to read

1
  • Hi, thanks for answering, I don't know how to read English very well so I will answer what I understood. In the code do not use the CREATE TABLE statement, I am working with mysql and phpmyadmin and it is a table of 10 columns in which 9 of those columns are varchar type and the last column is longblob type. I checked in phpmyadmin and the file is stored in binary. Commented Jan 2, 2021 at 21:48

1 Answer 1

1

When you insert the binary blob data (the image) into self.tabla_postulante using insert(), it will be converted to string (something like b'...'). You can change the binary blob data into hex string before inserting into self.tabla_postulante:

for row in rows:
    blob = row[3].hex()
    self.table_postulante.insert("", "end", values=(row[0], row[1], row[2], blob))

Then when you retrieve the row from self.tabla_postulante, you can convert back the hex string to bytes using bytes.fromhex():

def get_cursor(self, ev):
    ...
    blobImage = bytes.fromhex(row[3])
    readBlob = Image.open(io.BytesIO(blobImage))
    pic = ImageTk.PhotoImage(readBlob)
    foto = Label(self.Predecir_Frame, image=self.pic)
    foto.grid(row=1, column=0, pady=10, padx=30, sticky=W)
    foto.image = pic  # keep a reference to avoid garbage collected

Note that it is better to create foto outside get_cursor() and update the image using foto.configure(image=pic) inside the function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.