1

My app allow users to choose imgs and associate them to some text.

When the user choose an image from the photo roll, I copy it in the Documents directory.

As the user should choose the same img associating it to the same text or another one, how could I avoid to save duplicates of the same image?

I can't simply use fileExistsAtPath, because the name is generated on the fly.

Is there a way to know if the user is choosing an image already saved in the documents dir?

Sefran
  • 375
  • 6
  • 24

2 Answers2

0

You could calculate a checksum and compare it with checksums of photos already in the documents directory.

Jason Harwig
  • 43,743
  • 5
  • 43
  • 44
0

Have a look at Generate hash from UIImage, it shows two ways to compare two image with each other. The first one makes use of the md5 hash algorithm the other one uses NSData's isEqualToData in conjunction with the UIImagePNGRepresentation function.

However you could also compare file size and image dimensions first to avoid the more expensive approaches.

Community
  • 1
  • 1
Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
  • @Nick Weaver: every time the user choose an image I have to do the comparison with all the images in the documents directory. I thought first to compare file size and image dimensions and then use the md5 algorithm. As I use a sqlite3 db, do you know if it's better to save in the db also the md5 result for an image from the point of view of the efficiency? – Sefran May 14 '11 at 15:10
  • @Objnewbie Yes of course. The hash is some kind of meta data that does not change as long as the image doesn't change so keep in the db like the other information like the size. – Nick Weaver May 14 '11 at 16:04
  • @Nick Weaver: Thank you very much. I'm also considering the idea of using it like the filename. – Sefran May 14 '11 at 16:16
  • @Nick Weaver: I used the solution found following the link you gave, but the md5 is always different on the same image. Do you have an idea to how resolve this? – Sefran May 14 '11 at 20:14
  • @Objnewbie that is strange indeed. It could be interesting to store some very small reference pictures and dump the bytes to see if something is mutating. – Nick Weaver May 14 '11 at 20:25
  • @Nick Weaver: I found the problem. The first arg for CC_MD5 has to be "bytes" type of data. This is the working code:`-(NSString*)md5:(NSData*)input {unsigned char result[16];CC_MD5([input bytes], [input length], result);NSString *imageHash = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ]; return imageHash;}` – Sefran May 15 '11 at 09:42