案例所涉及到的内容:文件读取,写入。图片的形变,切割,缝合。
项目的流程如下:
1.检索文件
2.修改图片的尺寸比例成3:2
3.按3:2比例分割图片成一块块正方形
4.批量修改名字
5.按顺序名字把子图片合并完整的一张图
namespace ImageTool
{
class Program
{
private static string _fileNameWithoutExtension; //文件名
private static string _fileExtension;//扩展名
private static string _fileDirectory;//所属文件夹
private static string _targetImagePath = null;//分割图片所属的文件路径
private static string _imageSuffix; //设置图片后缀格式
public static class Data
{
public const string jpg = ".jpg";
public const string bmg = ".bmg";
public const string png = ".png";
public const string tiff = ".tiff";
public const string sprit = "\\";
private static string image = null;
public static string Image
{
get
{
if (image == null)
{
return image = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
}
else
{
return image;
}
}
}
}
enum StatusMessage
{
Null,
Move,
Unusual
}
static void MessageHandling(StatusMessage SM)
{
switch (SM)
{
case StatusMessage.Null:
Console.WriteLine("程序未启动...");
break;
case StatusMessage.Move:
Console.WriteLine("程序运行中...");
break;
case StatusMessage.Unusual:
Console.WriteLine("出现异常...");
return;
}
}
public Program() { }
static void Main()
{
Program program = new Program();
Console.WriteLine("输入修改图片的地址...");
var inputImgPath = Console.ReadLine();
string[] suffix = { ".exe" };
ArrayList Lists = FileSearch(inputImgPath, suffix);
Console.WriteLine("\n" + "检索到的文件列表如下: ");
if (Lists.Count == 0) {
Console.WriteLine("文件列表为null");
}
for (int i = 0; i < Lists.Count; i++)
{
Console.WriteLine("files[" + i + "]: "+Lists[i].ToString());
}
for (int i = 0; i < Lists.Count; i++)
{
if (File.Exists(Lists[i].ToString()))
{
_fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(Lists[i].ToString());
_fileExtension = System.IO.Path.GetExtension(Lists[i].ToString());
_fileDirectory = System.IO.Path.GetDirectoryName(Lists[i].ToString());
}
else
{
Console.WriteLine("文件不存在...");
MessageHandling(StatusMessage.Unusual);
return;
}
Console.WriteLine("\n#####################################################################");
Console.WriteLine("开始对文件:[--“" + Lists[i].ToString() + "”--]进行处理####");
var inputChangImgPath = _fileDirectory + Data.sprit + Data.Image;
string ChangImgPath = program.ChangImageSize(inputChangImgPath, Data.jpg);
program.CroppingToScale(ChangImgPath, Program._imageSuffix,false);
program.ChangeFilesName(_targetImagePath);
program.CombineImages(_targetImagePath, _targetImagePath + Data.sprit + Data.Image +"_"+ _fileNameWithoutExtension, Program._imageSuffix);
initialise();
}
System.Diagnostics.Process.Start(inputImgPath);//处理完成后打开相应的文件夹
Console.WriteLine("\n" + "---输入回车键退出程序---");
Console.ReadLine();
}
public static void initialise() {
_fileNameWithoutExtension = null;
_fileExtension = null;
_fileDirectory = null;
_targetImagePath = null;
_imageSuffix = null;
}
///
///
///
/// 路径
/// 排除文件名
///
public static ArrayList FileSearch(string path, string[] exception)
{
if (!Directory.Exists(path))
{
Console.WriteLine("不存在文件...");
return null;
}
int j = 0;
ArrayList mItem = new ArrayList();
DirectoryInfo search = new DirectoryInfo(path);
FileSystemInfo[] fsinfos = search.GetFileSystemInfos();
foreach (FileSystemInfo fsinfo in fsinfos)
{
if (!(fsinfo is DirectoryInfo))
{
for (int i = 0; i < exception.Length; i++)
{
if (fsinfo.Name.Contains(exception[i]) == false)
{
mItem.Add(fsinfo.FullName);
j++;
}
}
}
else
{
//这个用于检索当前文件夹下包含的所有子文件夹
//DirectoryInfo dtinfo = new DirectoryInfo(fsinfo.FullName);
//FileInfo[] f = dtinfo.GetFiles();
//foreach (FileInfo file in f)
//{
// for (int i = 0; i < exception.Length; i++)
// {
// if (file.Name.Contains(exception[i]) == false)
// {
// mItem.Add(file.FullName);
// j++;
// }
// }
//}
}
}
return mItem;
}
///
/// 修正图片比例,更改为3:2比例
///
/// 修正后图片生成地址
/// 图片格式
///
public string ChangImageSize(string destPath, string imageSuffix = Data.png)
{
var srcPath = _fileDirectory + Data.sprit + _fileNameWithoutExtension + _fileExtension;
Program._imageSuffix = imageSuffix;
try
{
Image inputImg = Image.FromFile(srcPath);
Console.WriteLine("\n" + "修正图片尺寸");
int imgWidth = inputImg.Width;
int imgHeight = inputImg.Height;
if (imgWidth < imgHeight)
{
Console.WriteLine("当前图像“imgWidth < imgHeight”,旋转为水平方向");
int heightAfter = (int)Math.Ceiling(imgHeight * 1.00);
int widthAfter = (int)Math.Ceiling(((heightAfter * 2) / 3) * 1.00);
int OffsetWidth = Math.Abs((widthAfter - imgWidth) / 2);
Bitmap newBmp = new Bitmap(heightAfter, widthAfter, PixelFormat.Format24bppRgb);
Graphics newBmpGraphics = Graphics.FromImage(newBmp);
newBmpGraphics.Clear(SystemColors.AppWorkspace);
Rectangle rect = new Rectangle(0, 0, imgHeight, imgWidth);
Rectangle rectangle = new Rectangle(0, OffsetWidth, imgHeight, imgWidth);
rectangle.Inflate(0, OffsetWidth);
inputImg.RotateFlip(RotateFlipType.Rotate90FlipNone);//图片旋转,与画布Graphics无关
newBmpGraphics.DrawImage(inputImg, rectangle, rect, GraphicsUnit.Pixel);
newBmpGraphics.Save();
var ChangFinishImagePath = destPath + _fileNameWithoutExtension + imageSuffix;
BitMapSave(newBmp, ChangFinishImagePath);
inputImg.Dispose();
newBmp.Dispose();
newBmpGraphics.Dispose();
Console.WriteLine("修正成功,图片地址另存为: " + ChangFinishImagePath);
return ChangFinishImagePath;
}else{
int widthAfter = (int)Math.Ceiling(imgWidth * 1.00);
int heightAfter = (int)Math.Ceiling(((widthAfter * 2) / 3) * 1.00);
int OffsetHeight = Math.Abs((heightAfter - imgHeight) / 2);
Bitmap newBmp = new Bitmap(widthAfter, heightAfter, PixelFormat.Format24bppRgb);
Graphics newBmpGraphics = Graphics.FromImage(newBmp);
newBmpGraphics.Clear(SystemColors.AppWorkspace);
Rectangle rect = new Rectangle(0, 0, imgWidth, imgHeight);
Rectangle rectangle = new Rectangle(0, OffsetHeight, imgWidth, imgHeight);
rectangle.Inflate(0, OffsetHeight);
newBmpGraphics.DrawImage(inputImg, rectangle, rect, GraphicsUnit.Pixel);
newBmpGraphics.Save();
var ChangFinishImagePath = destPath + _fileNameWithoutExtension + imageSuffix;
BitMapSave(newBmp, ChangFinishImagePath);
inputImg.Dispose();
newBmp.Dispose();
newBmpGraphics.Dispose();
Console.WriteLine("修正成功,图片地址为: " + ChangFinishImagePath);
return ChangFinishImagePath;
}
}
catch (OutOfMemoryException e)
{
Console.WriteLine("该文件没有有效的图像格式", e);
MessageHandling(StatusMessage.Unusual);
return null;
}
catch (Exception e)
{
Console.WriteLine(e);
MessageHandling(StatusMessage.Unusual);
return null;
}
}
///
/// 按比例分割图片
///
/// 导入地址
/// 图片格式
/// 是否删除源文件
///
public string CroppingToScale(string inputImgPath, string imageSuffix = Data.png, bool Bool = true)
{
if (!File.Exists(inputImgPath))
{
Console.WriteLine("修正后的图片找不到,文件不存在...");
MessageHandling(StatusMessage.Unusual);
return null;
}
// 装载要分隔的图片
Image inputImg = Image.FromFile(inputImgPath);
int imgWidth = inputImg.Width;
int imgHeight = inputImg.Height;
int cropWidth = imgWidth / 3;
int cropHeigth = imgHeight / 2;
//----------------------------------------------------------------------
ArrayList areaList = new ArrayList();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("");
sb.Append(System.Environment.NewLine);
int i = 0;
int pointY = 0;
for (int iHeight = 0; iHeight < 2; iHeight++)
{
int pointX = 0;
sb.Append("");
sb.Append(System.Environment.NewLine);
for (int iWidth = 0; iWidth < 3; iWidth++)
{
string fileName = string.Format("", _fileNameWithoutExtension, i, imageSuffix);
sb.Append("" + fileName + " ");
sb.Append(System.Environment.NewLine);
string s = string.Format("{0};{1};{2};{3}", pointX, pointY, cropWidth, cropHeigth);
Rectangle rect = new Rectangle(pointX, pointY, cropWidth, cropHeigth);
areaList.Add(rect);
pointX += cropWidth;
i++;
}
pointY += cropHeigth;
sb.Append(" ");
sb.Append(System.Environment.NewLine);
}
sb.Append("
");
Console.WriteLine("\n" + "检测是否存在子文件夹...");
string fileSonName = System.IO.Path.GetDirectoryName(inputImgPath) + Data.sprit + Data.Image + Data.sprit + _fileNameWithoutExtension;
_targetImagePath = fileSonName;
if (Directory.Exists(fileSonName) == false)
{
Console.WriteLine("文件夹不存在,创建中..");
Directory.CreateDirectory(fileSonName);
}
else
{
Console.WriteLine("生成图片文件夹存在,清空已有数据..");
DirectoryInfo dirInfo = new DirectoryInfo(fileSonName);
FileInfo[] files = dirInfo.GetFiles();
foreach (FileInfo file in files)
{
file.Delete();
Console.WriteLine("删除数据的路径 : " + file.DirectoryName + Data.sprit + file.Name);
}
Console.WriteLine("删除完毕!!!");
}
Console.WriteLine("\n" + "开始切割图片...");
for (int iLoop = 0; iLoop < areaList.Count; iLoop++)
{
Rectangle rect = (Rectangle)areaList[iLoop];
string fileName = fileSonName + Data.sprit + iLoop.ToString() + imageSuffix;
Bitmap newBmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format24bppRgb);
Graphics newBmpGraphics = Graphics.FromImage(newBmp);
Rectangle rectangle = new Rectangle(0, 0, rect.Width, rect.Height);
newBmpGraphics.DrawImage(inputImg, rectangle, rect, GraphicsUnit.Pixel);
newBmpGraphics.Save();
BitMapSave(newBmp, fileName);
Console.WriteLine("图片生成路径: " + fileName);
newBmp.Dispose();
newBmpGraphics.Dispose();
}
inputImg.Dispose();
if (Bool)
{
File.Delete(inputImgPath);
Console.WriteLine("\n" + "修正图已被删除(***默认处理***)...,路径: " + inputImgPath);
}
string html = sb.ToString();
Console.WriteLine("\n" + "Html(表): " + "\n" + html + "\n");
return html;
}
///
/// 修改分割文件名字
///
///
public void ChangeFilesName(string folderPath)
{
if (!Directory.Exists(folderPath)) {
MessageHandling(StatusMessage.Unusual);
return;
}
var files = new DirectoryInfo(folderPath).GetFiles();
Console.WriteLine("进行图片名字批处理..." + "\n" + "读取到的总数: " + files.Length);
if (files.Length == 0)
{
Console.WriteLine("未读取到文件");
MessageHandling(StatusMessage.Unusual);
return;
}
Console.WriteLine("开始修改... " + "\n\n" + "修改后名字: ");
int i = 0;
//文件名字处理在此修改
foreach (FileInfo file in files)
{
//string move_test = file.DirectoryName + Data.sprit + "New_image_" + Math.Abs(files.Length - int.Parse(file.Name.Remove(file.Name.IndexOf("."))));
//file.MoveTo(move_test + Data.png);
string move = file.DirectoryName + Data.sprit + "New_image_" + file.Name;
file.MoveTo(move);
Console.WriteLine("files[" + i + "]: " + move);
i++;
}
//int i = 0;
//while (i == files.Length)
//{
// switch (i)
// {
// case 0:
// files[i].MoveTo(files[i].DirectoryName + Data.sprit + "New_image_" + Math.Abs(files.Length - int.Parse(files[i].Name)));
// break;
// case 1:
// files[i].MoveTo(files[i].DirectoryName + Data.sprit + "New_image_" + Math.Abs(files.Length - int.Parse(files[i].Name)));
// break;
// case 2:
// files[i].MoveTo(files[i].DirectoryName + Data.sprit + "New_image_" + Math.Abs(files.Length - int.Parse(files[i].Name)));
// break;
// case 3:
// files[i].MoveTo(files[i].DirectoryName + Data.sprit + "New_image_" + Math.Abs(files.Length - int.Parse(files[i].Name)));
// break;
// case 4:
// files[i].MoveTo(files[i].DirectoryName + Data.sprit + "New_image_" + Math.Abs(files.Length - int.Parse(files[i].Name)));
// break;
// case 5:
// files[i].MoveTo(files[i].DirectoryName + Data.sprit + "New_image_" + Math.Abs(files.Length - int.Parse(files[i].Name)));
// break;
// }
// Console.WriteLine("Newfile: " + files[i].DirectoryName + Data.sprit + "New_image_" + Math.Abs(files.Length - int.Parse(files[i].Name)));
// i++;
//}
}
///
/// 缝合图片,根据名字顺序
///
/// 导入地址
/// 导出图片地址
/// 图片格式
private void CombineImages(string folderPath, string toPath, string imageSuffix = Data.png)
{
if (!Directory.Exists(folderPath))
{
MessageHandling(StatusMessage.Unusual);
return;
}
//var files = new DirectoryInfo(folderPath).GetFiles("*" + Data.png, SearchOption.TopDirectoryOnly);//目前检索到的文件只有图片,干脆全部获取
var files = new DirectoryInfo(folderPath).GetFiles();
if (files.Length == 0)
{
Console.WriteLine("文件不存在...");
MessageHandling(StatusMessage.Unusual);
}
Console.WriteLine("\n" + "进行图片缝合..." + "\n" + "处理中...Biubiubiu...");
var imgs = files.Select(f => Image.FromFile(f.FullName));
var finalWidth = imgs.Max(img => img.Width * 3);
var finalHeight = imgs.Max(img => img.Height * 2);
var finalImg = new Bitmap(finalWidth, finalHeight);
Graphics g = Graphics.FromImage(finalImg);
g.Clear(SystemColors.AppWorkspace);
var width = 0;
var height = 0;
for (int i = 0; i < files.Length; i++)
{
Image img = Image.FromFile(files[i].FullName);
g.DrawImage(img, width, height);
width += img.Width;
bool res = (i == 2) ? true : false;
if (res)
{
width = 0;
height += img.Height;
}
img.Dispose();
}
var finalImage = toPath + imageSuffix;
BitMapSave(finalImg, finalImage);
finalImg.Dispose();
g.Dispose();
Console.WriteLine("文件已保存,地址: " + finalImage);
Console.WriteLine("文件:[--" + _fileNameWithoutExtension + _fileExtension + "--]处理完毕!!!!");
}
///
/// 保存BitMap
///
///
/// 保存路径
/// 文件后缀
public static void BitMapSave(Bitmap bmp, string path)
{
switch (_imageSuffix.ToLower())
{
case ".bmg":
bmp.Save(path, ImageFormat.Bmp);
break;
case ".png":
bmp.Save(path, ImageFormat.Png);
break;
case ".jpg":
case ".jpeg":
bmp.Save(path, ImageFormat.Jpeg);
break;
case "gif":
bmp.Save(path, ImageFormat.Tiff);
break;
}
}
}
}