C# OpenCvSharp实现图片批量改名
作者:天天代码码天天
这篇文章主要为大家详细介绍了C#如何结合OpenCvSharp实现图片批量改名功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
效果
项目
代码
using NLog; using OpenCvSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; namespace OpenCvSharp_Demo { public partial class Form1 : Form { public Form1() { InitializeComponent(); NLog.Windows.Forms.RichTextBoxTarget.ReInitializeAllTextboxes(this); } private static Logger _log = NLog.LogManager.GetCurrentClassLogger(); private void Form1_Load(object sender, EventArgs e) { } string inPath = ""; string outPath = ""; DirectoryInfo folder; List<FileInfo> files=new List<FileInfo>(); String[] imageExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" }; /// <summary> /// 选择文件夹 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { inPath = ""; outPath = ""; files.Clear(); FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择文件路径"; if (dialog.ShowDialog() == DialogResult.OK) { inPath = dialog.SelectedPath; textBox1.Text = inPath; outPath = inPath + "\\out"; textBox2.Text = outPath; _log.Info("图片路径:" + inPath); _log.Info("保存路径:" + outPath); folder = new DirectoryInfo(inPath); var temp = folder.GetFiles("*.*", SearchOption.TopDirectoryOnly); foreach (FileInfo file in temp) { if (imageExtensions.Contains(file.Extension.ToLower())) { files.Add(file); } } _log.Info("一共["+ files .Count()+ "]张图片"); } } /// <summary> /// 修改名称 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { if (files.Count()==0) { return; } outPath = textBox2.Text; //目录不存在 则创建 if (!Directory.Exists(outPath)) { DirectoryInfo directoryInfo = new DirectoryInfo(outPath); //创建目录 directoryInfo.Create(); } else { DirectoryInfo outFolder=new DirectoryInfo(outPath); if (outFolder.GetFiles("*.*", SearchOption.AllDirectories).Length>0) { MessageBox.Show(outPath + "文件夹不为空,防止数据被覆盖,请更换!"); return; } } string oldName; string newName; Mat temp; int index = 0; foreach (FileInfo file in files) { oldName = file.Name; newName = index.ToString() + file.Extension; try { temp = new Mat(inPath + "\\" + oldName); //其他处理 ,例如 //图片缩放 //通道变换等 //…… Cv2.ImWrite(outPath + "\\" + newName, temp); _log.Info(oldName + "-->" + newName); index++; } catch (Exception ex) { _log.Info(oldName+"修改异常,异常信息:"+ex.Message); } } _log.Info("全部修改完成!"); } } }
到此这篇关于C# OpenCvSharp实现图片批量改名的文章就介绍到这了,更多相关C# OpenCvSharp图片改名内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!