qpixmap mysql,将blob图像数据加载到QPixmap中

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

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值