Qt 创建文件夹

由于项目需要,需要保存图片保存到文件夹。
演示步骤:
1.加载图片

Mat img = cv::imread("apple.jpg");//加载并显示图片
imshow("Image", img);

2.准备文件夹名和图片名
文件夹名=当前时间 年月日
图片名=当前时间 时分秒

QDateTime time = QDateTime::currentDateTime();
QString fullPath = time.toString("yyyyMMdd");
QString filePath = time.toString("MMddHHmmss");

3.判断文件夹存不存在,不存在则创建文件夹
参考:https://blog.csdn.net/lusirking/article/details/51644782

// 判断文件夹是否存在,不存在则创建
QDir dir(fullPath);
if(!dir.exists()){
    bool ismkdir = dir.mkdir(fullPath);
    if(!ismkdir)
        qDebug() << "Create path fail" << endl;
    else
        qDebug() << "Create fullpath success" << endl;
}
else{
    qDebug() << "fullpath exist" << endl;
}

滴滴滴:Create path fail
将:bool ismkdir = dir.mkdir(fullPath);改成:bool ismkdir = dir.mkpath(fullPath);会发现在当前目录里生成了20190801/20190801(在当前目录下生成了20190801文件夹,但是20190801文件夹里面又包含了一个20190801文件夹)。
参考:https://www.jianshu.com/p/cf39710e2e4b
因为我这里用的是dir.mkpath,所以实际上创建的目录为dir的路径 + fullpath的路径。难怪mkdir创建失败
将:bool ismkdir = dir.mkdir(fullPath);换成:bool ismkdir = Qdir().mkdir(fullPath);搞定,在执行目录下生成了一个空文件夹
4.保存图片

std::string str= QString("%1/%2.jpg").arg(fullPath).arg(filePath).toStdString();
imwrite(str, img);

完整main函数代码如下:

#include "opencvmat.h"
#include <QApplication>
#include <QDateTime>
#include <QDir>
#include <QString>
#include <QDebug>

#include <iostream>
#include <string.h>

#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Mat img = cv::imread("apple.jpg");//加载图片,延时2后自动关闭窗口
    imshow("Image", img);

    QDateTime time = QDateTime::currentDateTime();
    QString fullPath = time.toString("yyyyMMdd");
    QString filePath = time.toString("MMddHHmmss");

    // 判断文件夹是否存在,不存在则创建
    QDir dir(fullPath);
    if(!dir.exists()){
        bool ismkdir = QDir().mkdir(fullPath);
        if(!ismkdir)
            qDebug() << "Create path fail" << endl;
        else
            qDebug() << "Create fullpath success" << endl;
    }
    else{
        qDebug() << "fullpath exist" << endl;
    }

    std::string str= QString("%1/%2.jpg").arg(fullPath).arg(filePath).toStdString();
    imwrite(str, img);
    waitKey(2000);

    destroyAllWindows();

    //opencvMat w;
    //w.show();

    return a.exec();
}

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值