将blob图像数据加载到QPixmap中 [英] Load blob image data into QPixmap
问题描述
我正在使用PyQt4为前端GUI编写程序,该程序访问后端数据库(可以是MySQL或SQLite)。我需要在数据库中存储一些图像数据,下面是我用来将图像文件(JPEG格式)导入数据库中的blob数据字段的Python代码:
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
这部分工作正常。我的问题是如何从PyQt4中存储在数据库中的图像数据创建QPixmap对象。我目前的方法涉及以下步骤:
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 - cPickle& StringIO - > PIL图像对象
(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图像对象 - >临时图像文件
(2) PIL Image Object -->Temporary image file
(3)临时图像文件 - > QPixmap
(3) Temporary image file --> QPixmap
这种方法也可以。但如果我不必编写/读取临时图像文件会更好,这可能会减慢程序对用户交互的响应速度。我想我可以直接使用 QPixmap :: loadFromData()从存储在数据库中的blob数据加载,并希望有人在这里向我展示如何使用此函数的示例。
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
推荐答案
您可以使用QImage.fromData静态方法从字符串加载图像然后将其转换为像素图:
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)
这篇关于将blob图像数据加载到QPixmap中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!