开发者

C# reference comparison

Does someone know what might go wrong, when you attempt to compare two System.Drawing.Image entities?

开发者_如何学Python

I have some IEnumerable<Image> images, which is constructed iteratively using Image.FromFile(path) method.

But the following code yields the result I can't quite understand:

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

The thing is that the (Do something!) part never gets called.

Debugger shows that the image objects have a property called nativeImage, which, as I assume is a raw memory pointer, because System.Drawing.Image is implemented using marshalling.

This memory pointer is changed all the time and I guess some sort of cloning happens here, but I can't understand what should I actually do.

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

Thank you.


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 the ToList(), this obviously didn't work, I'm very stupid.

Thanks everyone.


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

var imageList = images.ToList();


By image1 == image2 you're only comparing the references of the image (not image as pixel by pixel).

By invoking Image.FromFile(path) you create 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 to compare images pixel by pixel, but of course you can implement your own mechanism for it (it doesn't look difficult).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜