QT保存(图像/字符)数据到本地为文件

功能一

  1. 保存图像数据到本地为JPG/PNG格式;
  2. 并且文件名为当前系统的日期时间。

函数实现

bool save_image(QImage imageData,QString curTime,QString savePath)
{
    //图片保存在当前目录下的文件夹
    if(imageData.save(QString("%1/%2.png").arg(savePath,curTime),"PNG",100))
        return true;    //保存成功
    else
        return false;   //保存失败
}

参数说明

  1. QImage imageData:图像数据

  2. QString curTime :为系统时间

//使用QT获取系统时间,并且转换为“2023-01-16 17:06:00” 格式的字符串
QDateTime curDateTime = QDateTime::currentDateTime();		        //获取当前系统时间
QString curTime = curDateTime.toString("yyyy-MM-dd hh:mm:ss:zzz");	//转换为string类型

扩展:

//将“2023-01-16 17:06:00” 格式的字符串,转换为QDateTime类型
QDateTime curDateTime(QDateTime::fromString(curTime,"yyyy-MM-dd hh:mm:ss:zzz"));
  1. QString savePath:保存文件路径

功能二

  1. 创建文件夹,并且保存字符为json/txt 等格式文件。

函数实现

#define DIRNAME "./DataDoc"		//这段代码写在头文件下面

//保存Json数据为文件
void SaveToJsonFile(Json::Value JsonMessage)
{
    //创建新目录
    QDir dir(QDir::currentPath());    //初始化当前目录
    if(!dir.exists(DIRNAME))          //判断新目录是否存在
        dir.mkdir(DIRNAME);           //不存在则创建
    dir.cd(DIRNAME);                  //进入新目录

    //创建新文件并打开
    QFile newFile(QString("%1/%2.json").arg(DIRNAME,curTime));
    if(!newFile.open(QIODevice::WriteOnly | QIODevice::Text))
        std::cout<<"Open NewFile failed!"<<std::endl;        //打开失败
    
    //写入Json数据到文件里
    newFile.write(JsonMessage.toStyledString().c_str());
    //关闭文件
    newFile.close();
}

参数说明

  1. Json::Value JsonMessage :为Json数据,格式如下
{
   "messageBody" : {
      "background_color" : "#DD22DD",
      "limit_style" : "timer",
      "limit_time" : "2023-01-12 15:00:03,2023-01-17 12:31:00",
      "text" : "这是一个提示文本测试",
      "text_color" : "#1A94E6",
      "text_direction" : "to_left",
      "text_fontSize" : "50",
      "text_id" : "111111",
      "text_scrollInterval" : "5"
   },
   "messageCommand" : "PLAY_PROMPT_TEXT",
   "messageState" : "wait"
}
posted @ 2023-01-16 17:54  程序员没有头发  阅读(843)  评论(0编辑  收藏  举报