《图形界面开发》批量重命名文件

来源:互联网 发布:怎么看淘宝商品编号 编辑:程序博客网 时间:2024/06/05 03:21

最近在做项目中需要用到大量的图片文件,然后从网络上获取到的图片命名是无规律的,为了使用简便,真好最近又在学习Qt界面编程语言,因此便用Qt写了一个批量重命名图片名字的小程序,在此分享出来供大家使用。
源代码及程序下载地址:

链接:http://pan.baidu.com/s/1kVmbDJp 密码:jznf

该程序使用C++语言+Qt开发而成。实现逻辑主要如下:
1.使用三个类分别完成不同功能,main函数作为程序入口,BGK.h文件作为编码转换的工具函数,实现GBK与Unicode之间的编码转换。

/************************//*Class:GBK*Function:*Convert GBK & Unicode    **@author:Yongchun Zha*@version:20170208*//************************/#pragma once#ifndef _GBK#define _GBK#include<QTextCodec>#include<string>using std::string;class GBK {public:    ////QString(Unicode)-->std::string(GBK)    static string FromUnicode(const QString&qstr)     {        QTextCodec* pCodec = QTextCodec::codecForName("GBK");        if (!pCodec)return "";        QByteArray arr = pCodec->fromUnicode(qstr);        string cstr = arr.data();        return cstr;    }    ////std::string(GBK)-->QString(Unicode)    static QString ToUnicode(const string&cstr)    {        QTextCodec* pCodec = QTextCodec::codecForName("GBK");        if (!pCodec)return "";        QString qstr = pCodec->toUnicode(cstr.c_str(),cstr.length());        return qstr;    }};#endif // !_GBK

RenameFiles.h和RenameFiles.cpp文件实现主界面接收信息

//RenamesFiles.h#pragma once#include <QtWidgets/QMainWindow>#include "ui_RenameFiles.h"#include<string>#include<slideBar.h>using namespace std;class RenameFiles : public QMainWindow{    Q_OBJECTpublic:    RenameFiles(QWidget *parent = Q_NULLPTR);private:    Ui::RenameFilesClass ui;private:    int mRule;    int fileSize;    QString mEnterPath;    QString mOutPath;    QString *mFileName;    QString *mFileRename;    enum    {        RULE_NUMBER,        RULE_WORD    };    void reName(int rules);private slots:    int OnbtnOK();    int OnbtnCancel();};
//RenameFiles.cpp#include "RenameFiles.h"#include<QDir>#include<QDebug>#include<QMessageBox>#include "GBK.h"RenameFiles::RenameFiles(QWidget *parent)    : QMainWindow(parent){    ui.setupUi(this);    //SIGNAL & SLOT    connect(ui.btnStart, SIGNAL(clicked()), this, SLOT(OnbtnOK()));    connect(ui.btnCancel, SIGNAL(clicked()), this, SLOT(OnbtnCancel()));}int RenameFiles::OnbtnOK(){    //get rule from UI    QString strRule = ui.comboBox->currentText();    if (strRule == "123...")        mRule = RULE_NUMBER;    else if (strRule == "一二三...")        mRule = RULE_WORD;    //rename file    reName(mRule);    //start process bar UI    slideBar mSildeBar(mFileName, mFileRename,fileSize,this);    mSildeBar.exec();    return 0;}int RenameFiles::OnbtnCancel(){    QApplication::exit();    return 0;}void RenameFiles::reName(int rules){    //get file path    if (ui.leEnterFilePath->text() != "" & ui.leOutFilePath->text() != "")    {        mEnterPath = ui.leEnterFilePath->text();        mOutPath = ui.leOutFilePath->text();        //load system's file        QDir dir(mEnterPath);        //search certain type of file        QStringList nameFilter;        nameFilter << "*.jpg";        //rename file        QStringList file = dir.entryList(nameFilter);        fileSize = file.size();        mFileName = new QString[fileSize];        mFileRename = new QString[fileSize];        for (int i = 0; i < fileSize; i++)        {            QString name = file[i];            QString namePath = ui.leEnterFilePath->text();            namePath.append("/");            namePath.append(name);            //qDebug() << name;            mFileName[i] = namePath;            if (rules == RULE_NUMBER)            {                string str = "/";                string str_num = to_string(i+1);                str.append(str_num);                str.append(".jpg");                name = GBK::ToUnicode(str);                QString nameOutPath = ui.leOutFilePath->text();                nameOutPath.append(name);                mFileRename[i] = nameOutPath;            }        }    }    else        QMessageBox::information(this, GBK::ToUnicode("提示信息"), GBK::ToUnicode("请输入完整的地址!"));}

sildeBar类实现进度条显示

//slideBar.h#pragma once#include <QWidget>#include "ui_slideBar.h"#include<QDialog>#include<Task.h>using namespace std;class slideBar : public QDialog{    Q_OBJECTpublic:    slideBar(QString* openfile, QString*savefile,int filesize, QWidget *parent = Q_NULLPTR);    ~slideBar();    virtual void timerEvent(QTimerEvent*event);private:    Ui::slideBar ui;    Task* mTask;    int timeID;};
//slideBar.cpp#include "slideBar.h"slideBar::slideBar(QString* openfile, QString* savefile, int filesize, QWidget *parent)    : QDialog(parent){    ui.setupUi(this);    //start task thread    mTask = new Task(openfile, savefile,filesize, NULL);    mTask->BeginTask();    //launch timer    timeID = startTimer(10);}slideBar::~slideBar(){}void slideBar::timerEvent(QTimerEvent*event){    if (event->timerId() == timeID)    {        int status = mTask->GetState();        int progress = mTask->GetProgerss();        ui.pbTaskBar->setValue(progress);        if (status == 1)        {            mTask->DestoryTask();            delete mTask;            killTimer(timeID);            this->accept();        }    }}

Task类是任务类,用已完成重命名操作

#pragma once#include <QObject>#include<QThread>#include<vector>#include<list>using namespace std;class Task : public QThread{    Q_OBJECTpublic:    Task(QString* openfile, QString* savefile, int filesize, QObject *parent);    ~Task();public:    int BeginTask();    void DestoryTask();    int GetState();    int GetProgerss();    int sourceFileSize;private:    QString* filePath;    QString* savePath;    int fileSize;    int outFileSize;    int ByteRead;//how much has read    int state;    void run();};
#include "Task.h"#include<GBK.h>#include<string>#include <QDebug>using namespace std;Task::Task(QString* openfile, QString* savefile, int filesize, QObject *parent)    : QThread(parent)    , filePath(openfile)    , savePath(savefile)    , sourceFileSize(filesize){    ByteRead = 0;}Task::~Task(){}int Task::GetState(){    return state;}int Task::GetProgerss(){    if (fileSize <= 0)return 0;    return ByteRead * 100 / fileSize;}//thread enter functionvoid Task::run(){    //qDebug() << "running...";    for (int i=0;i<sourceFileSize;i++)    {        ByteRead++;        //QThread::sleep(10);        //open source file        string gbk_filePath = GBK::FromUnicode(filePath[i]);        //replace '\' with '/'        for (int i = 0; i < gbk_filePath.length(); i++)        {            if (gbk_filePath[i] == '\\')                gbk_filePath[i] = '/';        }        FILE* fp = fopen(gbk_filePath.c_str(), "rb");        if (!fp)//open file error        {            state = -1;            return;        }        fseek(fp, 0, SEEK_END);        fileSize = ftell(fp);        fseek(fp, 0, SEEK_SET);        //open file which will save new file        string gbk_saveFile = GBK::FromUnicode(savePath[i]);        //replace '\' with '/'        for (int i = 0; i < gbk_saveFile.length(); i++)        {            if (gbk_saveFile[i] == '\\')                gbk_saveFile[i] = '/';        }        const char* gbk_charfile = gbk_saveFile.c_str();        FILE* fs = fopen(gbk_charfile, "wb");        char buf[1024];        while (true)        {            int n = fread(buf, 1, 1024, fp);            if (n <= 0) break;            fwrite(buf, 1, 1024, fs);        }        fclose(fp);        fclose(fs);    }    state = 1;}int Task::BeginTask(){    fileSize = 0;    ByteRead = 0;    state = 0;    start();    return 0;}void Task::DestoryTask(){    wait();}

至此,该程序代码部分基于完成了。

1 0