Skip to content
Advertisement

Display image from SQL DB in QLabel

The database stores images in varbinary format. I am getting data like this b’xffxd8xffxe0x00x10JFIFx00x01x01x01x00x00x00x00xffxe1x00ZExifx… I can save them if I use the code

    photo_path = r'C:1' + '\'
    cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=DESKTOP-8EKCG28RUSGUARD;DATABASE=RUSGUARDDB;UID=sa;PWD=123')
    cursor = cnxn.cursor()
    cursor.execute("SELECT Photo FROM [RusGuardDB].[dbo].[EmployeePhoto]")
    retrieved_bytes = cursor.execute("SELECT Photo FROM [RusGuardDB].[dbo].[EmployeePhoto]").fetchall()
    cursor.close()
    sum = numpy.array(retrieved_bytes)
    for a in range(len(sum)):
        sum1 = sum[a]
        with open(photo_path + 'new' + str(a) + '.jpg', 'wb') as new_jpg:
            new_jpg.write(sum1)

I don’t want to save pictures, i want show them directly in QLabel. How can i do this?

Advertisement

Answer

I finded solution for my problem.

retrieved_bytes = cursor.execute("SELECT Photo FROM [RusGuardDB].[dbo].[EmployeePhoto]").fetchone()
for row in retrieved_bytes:
            row_to_list = [elem for elem in row]
        pixmap = QPixmap()
        pixmap.loadFromData(bytearray(row_to_list))
        self.label1.setPixmap(pixmap)
4 People found this is helpful
Advertisement