I have some images with transparency that I am loading from the file system into UIImageView views. For my purpose I need to compare the image in the UIImageView with the file on the filesystem. So I do something like the following:
NSString *directoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imageFile = [NSString stringWithFormat:@"%@/image.png", directoryPath];
if ([[NSData dataWithContentsOfFile:imageFile] isEqualToData:UIImagePNGRepresentation([imageView image])]) {
NSLog(@"Equal");
} else {
NSString *dataDescription = [[[NSData dataWithContentsOfFile:feltFile] description] substringToIndex:100];
NSString *imageDescription = [[UIImagePNGRepresentation([backgroundImageView image]) description] substringToIndex:100]
NSLog(@"Unequal: %@ %@", dataDescription, imageDescription);
}
I know they are PNG images. Neither description is NULL when I print it. But they are unequal.
Why is this happening?
You can’t count on the PNG representation of an image staying the same bit-for-bit. There are multiple ways to encode the same image, and there is probably also metadata that can change between encodings.
Instead, you may be able to compare the images pixel by pixel. See the following for getting the pixel data of a UIImage: How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?