2

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?

Simon
  • 25,468
  • 44
  • 152
  • 266
Matthew Leffler
  • 1,386
  • 1
  • 19
  • 36

2 Answers2

5

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)?

Community
  • 1
  • 1
Daniel Dickison
  • 21,832
  • 13
  • 69
  • 89
1

UIImagePNGRepresentation() converts an image, in its generic type-agnostic form, into a PNG with standardized settings. Multiple PNG files can encode identical images, and when you read in a PNG you lose the associated meta data, which is then recreated (potentially differently) when you write out a new PNG file.

What is it you're trying to accomplish? Tell us and we can give you a better solution to your problem.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
  • Thanks for the response. Here's what I am trying to do: I have a list of resources that are stored with an md5 hash and I need to look up the image that is selected based on this hash. The md5 method I use requires a `NSData` object. Thus the problem: when the `NSData` does not equal the hash is correspondingly different and I don't find a matching resource. – Matthew Leffler Jan 07 '11 at 20:19
  • 2
    Can you elaborate? Based on that alone, you'll have to rethink how you look up your resources because writing out a new image is resource-intensive and will rarely give you the right answer. – Jonathan Grynspan Jan 07 '11 at 20:25
  • Thanks Jonathan – I was looking up a current image rather than writing a new one out. I think based on your answer and Daniel's I will have to store the hash of the images in an (separate) array that I can look up in. – Matthew Leffler Jan 10 '11 at 15:41