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++;
}
}
This is my button that will move all visually duplicated images comparing the first index (will make a nested one to go to next image and so on later). I create 2 path file strings. Then I use a while loop just to check if my count has reached the amount of files in the directory. After that it will end the loop.
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;
}
This method checks visually if an image is duplicated. Returns true
if it is.
I'm getting this exception:
The process cannot access the file because it is being used by another process.
It occurred on this line:
File.Move(originalPathFile + files[count2].ToString() + ".png", newPathFile + files[count2].ToString() + ".png");
When you open file using
new Bitmap(fileName)
you can't move file because it is in use. So dispose first that object and then try to move file. You can also use following approch where you can send filename instead of Bitmap and in compare function use using keywork which will automatically dispose object.}