Load blob image data into QPixmap

12,024

Solution 1

You can use the QImage.fromData static method to load an image from a string and then convert it to a pixmap:

 image_data = get_image_data_from_blob()
 qimg = QtGui.QImage.fromData(image_data)
 pixmap = QtGui.QPixmap.fromImage(qimg)

Solution 2

The approach suggested by Ants Aasma works and actually it is also OK to just use the following code:

image_data = cPickle.loads(str(s)) # s is fetched from DB 
qp = QPixmap() 
qp.loadFromData(image_data) 

Thanks a lot for all the help and information.

Share:
12,024
Tara
Author by

Tara

Updated on June 16, 2022

Comments

  • Tara
    Tara 7 months

    I am writing a program using PyQt4 for front-end GUI and this program accesses a back-end database (which can be either MySQL or SQLite). I need to store some image data in the database and below is the Python code I use to import image files (in JPEG format) to a blob data field in the database:

    def dump_image(imgfile):
        i = open(imgfile, 'rb')
        i.seek(0)
        w = i.read()
        i.close()
        return cPickle.dumps(w,1)
    blob = dump_image(imgfile)
    hex_str = blob.encode('hex') 
    # x"%s"%hex_str will be the string inserted into the SQL command
    

    This part works fine. My question is about how to create a QPixmap object from the image data stored in the database in PyQt4. My current approach involves the following steps:

    (1) Hex str in database -- cPickle&StringIO --> PIL Image Object

    def load_image(s):
        o = cPickle.loads(s)
        c = StringIO.StringIO()
        c.write(o)
        c.seek(0)
        im = Image.open(c)
        return im
    

    (2) PIL Image Object -->Temporary image file

    (3) Temporary image file --> QPixmap

    This approach also works fine. But it would be better if I don't have to write/read temporary image files which may slow down the program response to user interactions. I guess I could use QPixmap::loadFromData() to directly load from the blob data stored in the database and hope someone here could show me an example on how to use this function.

    TIA,

    Bing

    • balpha
      balpha over 13 years
      Why do you even use the PIL step? Qt is perfectly happy with loading JPEG data: docs.huihoo.com/pyqt/pyqt4/html/…
    • Tara
      Tara over 13 years
      I am sure Qt is able to load JPEG data. What I am looking for is a code snippet that converts the string encoded in the blob field to the QPixmap object. Thanks!
    • Tara
      Tara over 13 years
      I figured out I can just use QPixmap::loadFromData(cPickle.loads(s)) where s is the string data fetched from the blob field. Thanks for the help.