• 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文件夹内。
    主函数中关于
    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为图片的命名,根据自身喜好随便命名。实现效果如下:
  • 相关阅读:
    PHPStorm 支持 Element UI 语法提示
    npm
    谷歌浏览器插件
    RBAC
    git 知识点
    Laradock ppa加速
    vscode插件
    临时解决执行 Composer Install 返回 Killed 的问题
    单例设计模式(3种实现方式)
    log4j.properties 详解与配置步骤
  • 原文地址:https://www.cnblogs.com/xiaohai123/p/13563915.html
Copyright © 2020-2023  润新知