0

I am trying to compare images in folder(s) and storing diffrence on a 3rd folder.

While I am trying to compare between Image-1 and Image-2, the difference should be Image-3.

Difference between first two images (Image-3) is not showing full, only partial is showing, and I am getting GDI+ error

Code is

// Create the difference image.
bool are_identical = true;
Color eq_color = Color.White;
Color ne_color = Color.Red;

for (int x = 0; x < wid; x++)
{
    for (int y = 0; y < hgt; y++)
    {
        if (bm1.GetPixel(x, y).Equals(bm2.GetPixel(x, y)))
        {
            bm3.SetPixel(x, y, eq_color);
        }
        else
        {
            bm3.SetPixel(x, y, ne_color);
            are_identical = false;
            bm3.Save(@"C:\XPS Files\DiffrenceofImages\" + new1[i]);
        }
    }
}

GDI+ error occurs at

bm3.save(@"C:\XPS Files\DiffrenceofImages\" + new1[i]);

So the difference of image shows partial (until loop completed) e.g. if difference of 2 image is a circle, I get 80% of that circle.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

You should save the image outside the loop. If the pixels on the right are equal, the image isn't saved anymore. So you get a partial image.

// Create the difference image.
bool are_identical = true;
Color eq_color = Color.White;
Color ne_color = Color.Red;
for (int x = 0; x < wid; x++)
{
    for (int y = 0; y < hgt; y++)
    {
        if (bm1.GetPixel(x, y).Equals(bm2.GetPixel(x, y)))
        {
            bm3.SetPixel(x, y, eq_color);
        }
        else
        {
            bm3.SetPixel(x, y, ne_color);
            are_identical = false;
        }
    }
}
bm3.Save(@"C:\XPS Files\DiffrenceofImages\" + new1[i]);

If you want to speed it up, you could check here: Fast work with Bitmaps in C#

Community
  • 1
  • 1
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • It's probably a handle problem, because saving width*height times a image, could fail. (are the files directly closed? or are they still queued for the garbage collector) – Jeroen van Langen Jun 22 '15 at 09:09
  • It shouldn't, because any handle allocated as part of the save method should also be deallocated as part of the save method. – Lasse V. Karlsen Jun 22 '15 at 09:10
  • Moved the save out of loop now and i can spot the diffrences on new image. But GDI+ error occurs sporadically even if it's outside loop. Does it occur if same name image (diffrence image) already available ? – SANTISANTOSH_MAHAPATRA Jun 22 '15 at 09:16
  • An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll Additional information: A generic error occurred in GDI+. – SANTISANTOSH_MAHAPATRA Jun 22 '15 at 09:22
  • My Bad please ignore i was keeping the code (save) at wrong place (commented for referal) else { bm3.SetPixel(x, y, ne_color); are_identical = false; } } //I kept the code here before } bm3.Save(@"C:\ – SANTISANTOSH_MAHAPATRA Jun 22 '15 at 09:23