Comparative C # Comparison

Does anyone know what could go wrong if you try to compare two System.Drawing.Image objects?

I have several IEnumerable<Image> images that are iterated over using the Image.FromFile(path) method.

But the following code gives a result that I cannot understand:

 foreach (var image1 in images) { foreach (var image2 in images) { if (image1 == image2) { // (Do something!) } } } 

The fact is that the (Do something!) Part is never called.

The debugger shows that image objects have a property called nativeImage , which I assume is a raw memory pointer, since System.Drawing.Image is implemented using sorting.

This memory pointer is constantly changing, and I think there is some kind of cloning going on here, but I cannot figure out what I should actually do.

What am I doing wrong and how can I compare System.Drawing.Image objects taken from the same IEnumerable<> sequence to make sure they are the same?

Thanks.


Update

  var paths = new List<String> {"Tests/1_1.jpg", "Tests/1_2.jpg"}; IEnumerable<Image> images = paths.Select(path => Image.FromFile(path)).ToList(); foreach (var image1 in images) { foreach (var image2 in images) { if (ReferenceEquals(image1, image2)) { } } } 

Without ToList() this clearly did not work, I am very stupid.

Thanks to everyone.

+4
source share
2 answers

Remember that every time you call GetEnumerator , you will see new objects returned for each call to MoveNext . What you need to do is force iteration into the list.

 var imageList = images.ToList(); 
+2
source

In the image1 == image2 section, you only compare links to an image (and not an image as pixel by pixel).

By calling Image.FromFile(path) , you create a new image object every time you call this method (even if the path is the same), so they always have different references.

I don’t know if there is a method of comparing images by pixels, but, of course, you can implement your own mechanism for it (this does not look complicated).

+1
source

Source: https://habr.com/ru/post/1345584/


All Articles