打开对话框选择文件
二进制方式读取文件
转换成图像显示
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
原文地址:https://www.cnblogs.com/wxl845235800/p/10796886.html
时间: 2024-10-14 18:54:22