【QT】二進制讀取圖像文件並顯示


打開對話框選擇文件

二進制方式讀取文件

轉換成圖像顯示

 

 

void MainWindow::showImage()
{
    //打開文件對話框

    QString lastPath="D:/Englishpath/QTprojects/DATA/videoData";
    fileName = QFileDialog::getOpenFileName(this,"OpenFile", lastPath);
    if(fileName.isEmpty())
    {
        QMessageBox::information(this,"Error Message","Select File Failed");
        return;
    }
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly))
    {
        QMessageBox::information(NULL,"失敗提示","打開失敗",QMessageBox::Ok,QMessageBox::Ok);
        return;
    }
//    QTextStream in(&file);
//    ui->textEdit->setText(in.readAll());

    //類型轉換為可以被ifstream使用的
    QString str =fileName;
    char *s; QByteArray//QString轉換為char*
    ba = str.toLatin1();
    s = ba.data();

    // [1]得到二進制數據;
    using std::ifstream;
    ifstream i_f_stream(s,ifstream::binary);
    i_f_stream.seekg(0, i_f_stream.end);
    int length = i_f_stream.tellg();
    i_f_stream.seekg(0, i_f_stream.beg);
    char *buffer = new char[length];
    i_f_stream.read(buffer, length);//一次性讀取
    i_f_stream.close();

    // [2]緩存數據重構;
    QByteArray byteArray(buffer, length);

    // [3] 構建圖片對象並載入二進制數據;
    QImage img;
    img.loadFromData(byteArray, "png");

    // [4] 結果檢測(將圖片保存到某一目錄、用label顯示);
    img.save(QString("test.bmp"), "png");
    ui->d_label->setPixmap(QPixmap::fromImage(img));

    delete [] buffer;

//    QDataStream in(&file);
//    while( !in.atEnd())
//    {
//        QByteArray s;
//        in >> s;
//        file.close();
//        qDebug()<<s<<endl;
//    }
}

 

【轉載自】

std::ifstream以二進制方式讀取圖片文件,用Qt再將其轉為圖片(QImage::loadFromData()函數使用) - ypy9323的博客 - CSDN博客 https://blog.csdn.net/ypy9323/article/details/81835530


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM