基于C++跨平台文件批量重命名,图像批量resize源码

基于C++跨平台文件批量重命名,图像批量resize源码。需要库opencv。跨平台编译时主要是文件路径的斜杠不统一。

#include 
#include 
#include 

//通过注释选择平台
#define __WIN32__
//#define __linux__
using namespace cv;
using namespace std;

/********************使用前修改路径***********************/
string patternFiles = "C:\\Users\\bb\\Desktop\\1\\*.jpg";//修改路径
/********************************************************/

#if defined(__WIN32__)//跨平台
std::string pathPrefix = patternFiles.substr(0, patternFiles.rfind('\\') + 1);//获取文件路径前缀
#elif defined(__linux__)//跨平台
std::string pathPrefix = patternFiles.substr(0, patternFiles.rfind('/') + 1);//获取文件路径前缀
#endif

int main() {
	vector filePath;
	cv::glob(patternFiles, filePath, false);
	int filesNum = filePath.size(), charWidth = 0;//获取文件数量,并且自动设置重命名的数字宽度
	while (filesNum) { filesNum /= 10; charWidth++; }//计算控制命名的宽度,如4为宽度为0001

	cout << "重命名功能会覆盖掉当前文件夹中用 纯数字+后缀 命名的文件,导致文件丢失。请谨慎使用!"<> choiceModel;

	if (choiceModel == 1) {
		//模式1,批量重命名
		for (int i = 0; i < filePath.size(); i++) {
			std::string pathSuffix = filePath[i].substr(filePath[i].rfind('.'));//获取文件路径后缀
			std::ostringstream newName;//通过字符串流来生成指定的路径
			newName << pathPrefix << setw(charWidth) << setfill('0') << i << pathSuffix;
			int renameFlag = rename(filePath[i].c_str(), newName.str().c_str());//重命名并返回值
			cout << filePath[i] << " --> " << newName.str() << "  result=" << (!renameFlag)<< endl;
		}
	}
	else if (choiceModel == 2) {
		//模式2,图像resize+转jpg
		int W = 0, H = 0;
		cout << "输入resize图像尺寸 (大于0的整数,均输入1则不resize) W H" << endl;
		cin >> W;
		cin >> H;
		for (int i = 0; i < filePath.size(); i++) {
			Mat image = imread(filePath[i]); //读取当前图像
			if (W <= 0 || H <= 0) { cout << "输入图像尺寸错误,程序结束!"; return 0; }
			if (W != 1 || H != 1) { cv::resize(image, image, Size(W,H)); cout << "RESIZE - "; }
			string fileName = filePath[i].substr(0, filePath[i].rfind('.')) + ".jpg";
			cout << fileName << endl;
			imwrite(fileName, image); //写入jpg文件
		}
	}
	else if (choiceModel == 3) {
		//模式3,图像resize+转jpg+批量重命名
		int W = 0, H = 0;
		cout << "输入resize图像尺寸 (大于0的整数,均输入1则不resize) W H" << endl;
		cin >> W;
		cin >> H;

		for (int i = 0; i < filePath.size(); i++) {
			Mat image = imread(filePath[i]); //读取当前图像
			if (W <= 0 || H <= 0) { cout << "输入图像尺寸错误,程序结束!"; return 0; }
			if (W != 1 || H != 1) { cv::resize(image, image, Size(W, H)); cout << "RESIZE - "; }

			std::ostringstream newName;//通过字符串流来生成指定的路径
			newName << pathPrefix << setw(charWidth) << setfill('0') << i << ".jpg";
			bool imwriteFlag = imwrite(newName.str(), image); //写入jpg文件
			cout << filePath[i] << " --> " << newName.str() << "  result=" << imwriteFlag << endl;
		}
	}
	else {
		cout << "请填写自己的代码" << endl;
		//手动实现自己的代码
	}
	return 0;
}

你可能感兴趣的:(C++,windows,linux,批量替换,opencv)