Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two ways of comparing UIImages show different results. Which one to believe?

Tags:

iphone

uiimage

I'm trying to compare two UIImages. If i compare it like this:

if ([UIImagePNGRepresentation ( holderImage) isEqualToData:UIImagePNGRepresentation([UIImage imageNamed:@"empty_image.png"])])
            NSLog(@"empty image");
        else
            NSLog(@"not empty image");

the result is YES, THEY'RE EQUAL

if i'm doing the following

` if ([holderImage isEqual:[UIImage imageNamed:@"empty_image.png"]])
            NSLog(@"empty image");
        else
            NSLog(@"not empty image"); `

the result is NO, THEY'RE NOT

The situation is pretty complicated because:

1) Images MUST BE (it means i'm pretty much sure)equal so i would believe the first one unless

2) isEqual comparison always gives true result on other images.

So i'm completely confused. What do you think about that? Btw the holderImage was just taken from NSUserDefaults. Do you think it might be changed somehow while being stored in NSUserDefaults so that isEqual comparison is lying now?

like image 434
Andrey Chernukha Avatar asked Jan 04 '12 10:01

Andrey Chernukha


2 Answers

The isEqual method on UIImage looks a the pointer/hash of the object where as the isEqual method on NSData will look it the bytes are the same.

The isEqual used by most object are based on hash. In the Apple documentation it is specified that NSData implements the isEqual method in a different way.

Two data objects are equal if they hold the same number of bytes, and if the bytes at the same position in the objects are the same.

like image 173
rckoenes Avatar answered Oct 27 '22 00:10

rckoenes


PivotalCoreKit provides a helper for comparing the images via bytes. This will pass if the images are created via different sources (eg. [UIImage -UIImageNamed] and [UIImage initWithData:], unlike UIImagePNGRepresentation().

- (BOOL)isEqualToByBytes:(UIImage *)otherImage {
    NSData *imagePixelsData = (NSData *)CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage));
    NSData *otherImagePixelsData = (NSData *)CGDataProviderCopyData(CGImageGetDataProvider(otherImage.CGImage));

    BOOL comparison = [imagePixelsData isEqualToData:otherImagePixelsData];

    CGDataProviderRelease((CGDataProviderRef)imagePixelsData);
    CGDataProviderRelease((CGDataProviderRef)otherImagePixelsData);
    return comparison;
}
like image 37
Joe Masilotti Avatar answered Oct 26 '22 23:10

Joe Masilotti