private void button4_Click(object sender, EventArgs e)
{
string originalPathFile = @"C:\Users\user\Downloads\CaptchaCollection\Small\Sorting\";
string newPathFile = @"C:\Users\user\Downloads\CaptchaCollection\Small\Sorted\";
bool endInner = false;
int count2 = 1;
while (!endInner)
{
var files = Directory.GetFiles(originalPathFile).Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension)).Where(name => { int number; return int.TryParse(name, out number); }).Select(name => int.Parse(name)).OrderBy(number => number).ToArray();
Bitmap im1 = new Bitmap(originalPathFile + files[0].ToString() + ".png");
Bitmap im2 = new Bitmap(originalPathFile + files[count2].ToString() + ".png");
if (compare(im1, im2))
{
// if it's equal
File.Move(originalPathFile + files[count2].ToString() + ".png", newPathFile + files[count2].ToString() + ".png");
MessageBox.Show(files[count2].ToString() + " was removed");
}
if (count2 >= files.Length - 1) // checks if reached last file in directory
{
endInner = true;
}
count2++;
}
}
这是我的按钮,它将移动与第一个索引进行比较的所有视觉上重复的图像(将嵌套一个以转到下一个图像,以此类推)。我创建了 2 个路径文件字符串。然后我使用一个while循环来检查我的计数是否达到了目录中的文件数量。之后它将结束循环。
private bool compare(Bitmap bmp1, Bitmap bmp2)
{
bool equals = true;
Rectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);
BitmapData bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat);
BitmapData bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp2.PixelFormat);
unsafe
{
byte* ptr1 = (byte*)bmpData1.Scan0.ToPointer();
byte* ptr2 = (byte*)bmpData2.Scan0.ToPointer();
int width = rect.Width * 3; // for 24bpp pixel data
for (int y = 0; equals && y < rect.Height; y++)
{
for (int x = 0; x < width; x++)
{
if (*ptr1 != *ptr2)
{
equals = false;
break;
}
ptr1++;
ptr2++;
}
ptr1 += bmpData1.Stride - width;
ptr2 += bmpData2.Stride - width;
}
}
bmp1.UnlockBits(bmpData1);
bmp2.UnlockBits(bmpData2);
return equals;
}
此方法直观地检查图像是否重复。true
如果是则返回。
我得到了这个例外:
The process cannot access the file because it is being used by another process.
它发生在这一行:
File.Move(originalPathFile + files[count2].ToString() + ".png", newPathFile + files[count2].ToString() + ".png");