c++代码批量修改图片名称(重命名)实例及运行结果

本文介绍了一个使用VS2013和OpenCV的C++程序,该程序能够批量地将指定文件夹内的图片按统一格式进行重命名。代码通过读取特定格式(如.png)的图片文件,将其编号并更新文件名,适用于图像处理前的数据预处理阶段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境vs2013+opencv2.4.9+win10

c++代码

#include <iostream>  
#include <sstream>//格式转换,这里是int转为string
#include <string>  
#include <io.h>  //进行系统文件操作的头文件

using namespace std;
const int N = 3;//假如少于100张,N=2,则编号1~99;N=3,则编号01~099,N=4,则编号0001~0099
const string fileType = ".png";//需要重命名图片的格式
string int2string(int n, int i);//类型转换函数

int main()
{
	_finddata_t file;   // 查找文件的类
	string fileDirectory = "C:\\Users\\2105Share\\Desktop\\trafficSignImage"; //文件夹目录,自己修改
	string buffer = fileDirectory + "\\*" + fileType;
	//long hFile;//win7系统
	intptr_t hFile;//win10系统
	hFile = _findfirst(buffer.c_str(), &file); //找第一个文件

	if (hFile == -1L) 
		cout << "没有指定格式的图片" << endl;//没有指定格式的图片
	else
	{
		int i = 0;
		string newFullFilePath;
		string oldFullFilePath;
		string strName;
		do
		{
			oldFullFilePath.clear();
			newFullFilePath.clear();
			strName.clear();

			oldFullFilePath = fileDirectory + "\\" + file.name;
			++i;
			strName = int2string(N, i); //类型转换
			newFullFilePath = fileDirectory + "\\" + strName + fileType;

			int c = rename(oldFullFilePath.c_str(), newFullFilePath.c_str());//重命名
			if (c == 0)
				cout << "重命名成功"<<strName<<fileType<<endl;
			else
				cout << "重命名失败" << strName << fileType << endl;

		} while (_findnext(hFile, &file) == 0);  
		_findclose(hFile);
	}

	system("pause");
	return 0;
}

string int2string(int n, int i)//类型转换函数
{
	char s[BUFSIZ];
	sprintf_s(s, "%d", i);
	int len = strlen(s);
	if (len > n)
	{
		cout << "输入的N太小!";
	}
	else
	{
		stringstream Num;
		for (int i = 0; i < n - len; i++)
			Num << "0";
		Num << i;

		return Num.str();
	}
}

运行结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值