posted on 2006-04-12 01:10 birdshome 阅读(26894) 评论(85) 编辑 收藏
using System; using System.IO; using System.Drawing; public class DeleteSameImage { public void Delete(string srcDir) { //初始化 string[] all = Directory.GetFiles(srcDir, "*.png"); ImageInfo[] imgFiles = new ImageInfo[all.Length]; int count = 0; foreach (string filename in all) { imgFiles[count] = new ImageInfo(); imgFiles[count].filemane = filename; imgFiles[count].same = false; count++; } //比对,删除相同的图像 for (int i = 0; i < imgFiles.Length; i++) { if (imgFiles[i].same == true) { continue; } //读原图颜色 Color[,] colorSrc = readImageColor(imgFiles[i].filemane); //与每一个图做比对 for (int iNext = i + 1; iNext < imgFiles.Length; iNext++) { if (imgFiles[iNext].same == true) { continue; } if (compareImage(colorSrc, imgFiles[iNext].filemane) == true) { imgFiles[iNext].same = true; //删除相同的图像 File.Delete(imgFiles[iNext].filemane); } System.Windows.Forms.Application.DoEvents(); } } } private Color[,] readImageColor(string filename) { Bitmap imgSrc = new Bitmap(filename); Color[,] colorSrc = new Color[imgSrc.Width, imgSrc.Height]; for (int row = 0; row < imgSrc.Height; row++) { for (int col = 0; col < imgSrc.Width; col++) { colorSrc[col, row] = imgSrc.GetPixel(col, row); } } return colorSrc; } private bool compareColor(ref Color src, ref Color dest) { if (src.R != dest.R || src.G != dest.G || src.B != dest.B) { return false; } return true; } private bool compareImage(Color[,] colorSrc, string filename) { Bitmap imgDest = new Bitmap(filename); if (colorSrc.GetLength(0) != imgDest.Width || colorSrc.GetLength(1) != imgDest.Height) { return false; } bool same = true; for (int row = 0; row < imgDest.Height; row++) { for (int col = 0; col < imgDest.Width; col++) { Color colorDest = imgDest.GetPixel(col, row); if (compareColor(ref colorSrc[col, row], ref colorDest) != true) { same = false; break; } } if (same != true) { break; } } imgDest.Dispose(); return same; } } public class ImageInfo { public string filemane = ""; //图像路径 public bool same = false; //与某个图像相同 }