天天看點

Qt 關于圖檔打開,另存為,儲存到指定位置操作

Qt 關于圖檔打開,另存為,儲存到指定位置操作(轉載)

在頭檔案mainwindow.h中先聲明以下類:

1 #include <QImage>
2 #include <QPixmap>
3 #include <QFileDialog>
4 #include <QMessageBox>
5 #include <QScreen>
6 #include <QGuiApplication>      

在私有對象下聲明這幾個變量,用于存放檔案夾位址。

1 /* 儲存路徑*/
2 QString runPath;
3 QString hglpName;
4 QString hglpPath;      

再在設計界面上拖放一個标簽和三個按鈕,按鈕分别命名為打開圖檔,另存為和儲存。其中儲存是儲存到程式運作檔案下的photo檔案夾内。

Qt 關于圖檔打開,另存為,儲存到指定位置操作

主函數中關于

1 runPath = QCoreApplication::applicationDirPath();       //擷取exe路徑
2 hglpName = "photo";
3 hglpPath = QString("%1/%2").arg(runPath).arg(hglpName);      

打開按鈕槽函數實作:

1 void MainWindow::on_pushButton_clicked()
 2 {
 3     QString filename=QFileDialog::getOpenFileName(this,tr("選擇圖像"),"",tr("Images (*.png *.bmp *.jpg)"));
 4     if(filename.isEmpty())
 5         return;
 6     else
 7     {
 8         QImage img;
 9         if(!(img.load(filename))) //加載圖像
10         {
11             QMessageBox::information(this, tr("打開圖像失敗"),tr("打開圖像失敗!"));
12             return;
13         }
14         ui->label->setPixmap(QPixmap::fromImage(img.scaled(ui->label->size())));
15     }
16 }      

另存為按鈕槽函數實作;

1 void MainWindow::on_pushButton_2_clicked()
2 {
3     QString filename1 = QFileDialog::getSaveFileName(this,tr("Save Image"),"",tr("Images (*.png *.bmp *.jpg)")); //選擇路徑
4     QScreen *screen = QGuiApplication::primaryScreen();
5     screen->grabWindow(ui->label->winId()).save(filename1);
6 }      

儲存按鈕槽函數實作;

1 void MainWindow::on_pushButton_3_clicked()
2 {
3     QScreen *screen = QGuiApplication::primaryScreen();
4     screen->grabWindow(ui->label->winId()).save(QString("%1/34.jpg").arg(hglpPath));
5 }      

其中34為圖檔的命名,根據自身喜好随便命名。實作效果如下:

Qt 關于圖檔打開,另存為,儲存到指定位置操作