我正在使用sqlite3数据库进行图像查看器pyqt gui应用程序。但我无法将图像上传到数据库。我怎么能这样做?
def open(ui):
fname = QFileDialog.getOpenFileName(ui, 'Open file','c:\\',"Image files (*.jpg *.gif)")
ui.FirmEditLogoEntry.setText(fname)
我可以获取文件名。但无法转换为二进制。
请帮我这样做。 谢谢
答案 0 :(得分:2)
使用QFileDialog
只获取文件的名称,您必须使用该信息来读取文件的字节,并使用QFile
并将该数据保存在BLOB
s中。在下一部分中,我展示了一个例子:
import sys
from PyQt4.QtGui import *
from PyQt4.QtSql import *
from PyQt4.QtCore import *
def createConnection():
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName(':memory:')
if not db.open():
QMessageBox.critical(None, "Cannot open database",
"Unable to establish a database connection.\n"
"This example needs SQLite support. Please read the Qt SQL "
"driver documentation for information how to build it.\n\n"
"Click Cancel to exit.",
QMessageBox.Cancel)
return False
query = QSqlQuery()
return query.exec_('''CREATE TABLE IF NOT EXISTS imgTable
(id INTEGER primary key AUTOINCREMENT, filename TEXT, imagedata BLOB)''')
class Widget(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
vbox = QVBoxLayout(self)
self.load_btn = QPushButton("Select Image")
self.combo = QComboBox()
self.label = QLabel()
self.model = QSqlTableModel()
self.model.setTable("imgTable")
self.model.select()
self.combo.setModel(self.model)
self.combo.setModelColumn(1)
vbox.addWidget(self.load_btn)
vbox.addWidget(self.combo)
vbox.addWidget(self.label)
self.load_btn.clicked.connect(self.load_image)
self.combo.currentIndexChanged.connect(self.on_change_select)
def on_change_select(self, row):
ix = self.combo.model().index(row, 2)
pix = QPixmap()
pix.loadFromData(ix.data())
self.label.setPixmap(pix)
def load_image(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', QDir.currentPath(), "Image files (*.jpg, *.gif, *.png)")
if fname:
self.saveImage(fname)
def saveImage(self, filename):
file = QFile(filename)
if not file.open(QIODevice.ReadOnly):
return
ba = file.readAll()
name = QFileInfo(filename).fileName()
record = self.model.record()
record.setValue("filename", name)
record.setValue("imagedata", ba)
if self.model.insertRecord(-1, record):
self.model.select()
if __name__ == '__main__':
app = QApplication(sys.argv)
if not createConnection():
sys.exit(-1)
w = Widget()
w.show()
sys.exit(app.exec_())