pyqt二進制和圖片的轉換

參考:http://blog.chinaunix.net/uid-28194872-id-3516936.htmlhtml

 

MySQL數據庫要想插入圖片,其字段須要是BLOB類型。
BLOB (binary large object),二進制大對象,是一個能夠存儲二進制文件的容器。sql

在計算機中,BLOB經常是數據庫中用來存儲二進制文件的字段類型。數據庫

BLOB是一個大文件,典型的BLOB是一張圖片或一個聲音文件,因爲它們的尺寸,必須使用特殊的方式來處理(例如:上傳、下載或者存放到一個數據庫)。ui

MySQL中,BLOB是個類型系列,包括:TinyBlob、Blob、MediumBlob、LongBlob,這幾個類型之間的惟一區別是在存儲文件的最大大小上不一樣。

MySQL的四種BLOB類型this

類型 大小(單位:字節)
TinyBlob 最大 255.net

Blob 最大 65Kunix

MediumBlob 最大 16Morm

LongBlob 最大 4G

選擇圖片文件:
QString strImage = QFileDialog::getOpenFileName(
this,server

"Please Select image file",htm

g_strCurrentDir,

"Image Format (*.png *.jpg *.bmp *.gif)");

if (strImage.isNull())

{
return;

}

g_strCurrentDir = QDir(strImage).absolutePath();

ui->labelPic->setPixmap(QPixmap(strImage).scaled(ui->labelPic->size()));

//保存圖片到數據庫中:
QByteArray bytes;

QBuffer buffer(&bytes);

buffer.open(QIODevice::WriteOnly);

ui->labelPic->pixmap()->save(&buffer, "JPG");

QByteArray data;

QSqlQuery query;
QString path = strImage;

QFile* file=new QFile(path); //fileName爲二進制數據文件名

file->open(QIODevice::ReadOnly);
data = file->readAll();

 file->close();

Variant var(data);

QString sql = "insert into images(Image) values(?)";

 query.prepare(sql);

query.addBindValue(var);

if(!query.exec())

{

qDebug()<<query.lastError().text().toLocal8Bit().data();

}

 else

{

qDebug()<<"Insert success";
}

}



//顯示數據庫裏的圖片
     QSqlQuery q("SELECT * FROM images WHERE PicNum = 108");
   while (q.next())
    {
    if (q.isNull(0) == false)
    {
    QPixmap photo;
    ui->num->setText(q.value(0).toString());
    photo.loadFromData(q.value(1).toByteArray(), "JPG");
    ui->UserPicLabel->setPixmap(photo);
     qDebug()<<"Query success";
    }
    else
    {
        qDebug()<<"Query failed";
    }
   }
//鏈接數據庫
#ifndef CONNECTION_H
#define CONNECTION_H
#include 
#include 
#include 
#include 
#include 
#include 
static bool createConnection()
{

   QSqlDatabase db =QSqlDatabase::addDatabase("QMYSQL");
   db.setDatabaseName("test");
   db.setHostName("172.17.54.133");
   db.setPort(3306);
   db.setUserName("root");
   db.setPassword("213517");
   if(!db.open())
   {
       QMessageBox::critical(0,qApp->tr("Cannot connect server"),qApp->tr("Unable to establish a database connection.\n"),QMessageBox::Cancel);
       return false;
       qDebug()<<"Connect MySql error!";
   }

   return true;

}


#endif // CONNECTION_H

注意:圖片插入數據庫和顯示時其格式必須是和圖片自己的格式對應的,否則不能顯示。
ex:  photo.loadFromData(q.value(1).toByteArray(), "JPG");
源碼下載:   SQLPicTest.rar
數據庫下載:test.rar

相關文章
相關標籤/搜索