QT关于图片打开,另存为,保存到指定位置操作

在头文件mainwindow.h中先声明以下类:
#include <QImage>
#include <QPixmap>
#include <QFileDialog>
#include <QMessageBox>
#include <QScreen>
#include <QGuiApplication>
在私有对象下声明这几个变量,用于存放文件夹地址。
    /* 保存路径*/
    QString runPath;
    QString hglpName;
    QString hglpPath;
再在设计界面上拖放一个标签和三个按钮,按钮分别命名为打开图片,另存为和保存。其中保存是保存到程序运行文件下的photo文件夹内。

主函数中关于
runPath = QCoreApplication::applicationDirPath();       //获取exe路径
hglpName = "photo";
hglpPath = QString("%1/%2").arg(runPath).arg(hglpName);
打开按钮槽函数实现:
void MainWindow::on_pushButton_clicked()
{
    QString filename=QFileDialog::getOpenFileName(this,tr("选择图像"),"",tr("Images (*.png *.bmp *.jpg)"));
    if(filename.isEmpty())
        return;
    else
    {
        QImage img;
        if(!(img.load(filename))) //加载图像
        {
            QMessageBox::information(this, tr("打开图像失败"),tr("打开图像失败!"));
            return;
        }
        ui->label->setPixmap(QPixmap::fromImage(img.scaled(ui->label->size())));
    }
}
另存为按钮槽函数实现;

void MainWindow::on_pushButton_2_clicked()
{
    QString filename1 = QFileDialog::getSaveFileName(this,tr("Save Image"),"",tr("Images (*.png *.bmp *.jpg)")); //选择路径
    QScreen *screen = QGuiApplication::primaryScreen();
    screen->grabWindow(ui->label->winId()).save(filename1);
}
保存按钮槽函数实现;
void MainWindow::on_pushButton_3_clicked()
{
    QScreen *screen = QGuiApplication::primaryScreen();
    screen->grabWindow(ui->label->winId()).save(QString("%1/34.jpg").arg(hglpPath));
}
其中34为图片的命名,根据自身喜好随便命名。实现效果如下:





Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐