17

How do you get a person's image from an iPhone address book?

Trojan
  • 2,256
  • 28
  • 40
Madhup Singh Yadav
  • 8,110
  • 7
  • 51
  • 84

3 Answers3

42

You can do it like this....

NSData  *imgData = (NSData *)ABPersonCopyImageData(person);

UIImage  *img = [UIImage imageWithData:imgData];

where person is of type ABRecordRef. Now, as CFData and NSData are toll-free bridged, you can simply type cast CFData to NSData and get the image

Hope this helps.

Madhup Singh Yadav
  • 8,110
  • 7
  • 51
  • 84
  • just a note that "imgaeWithData:imgData" in the last line of the code snippet should read "imageWithData:imgData". I fixed it – Peter Johnson May 17 '11 at 10:06
  • Please note that this might not be the image that the users expects since it is not the cropped version of the image. See [ChangUZ's answer](http://stackoverflow.com/a/6953492/784318) – Besi Jan 23 '12 at 14:06
  • @Besi But with out mentioning any image format is advantageous as while populating the images in cells of table view,we use image view as accessory view,because it automatically resizes the image and sets each image in unique format(same dimensions) :) – Eshwar Chaitanya Jul 18 '12 at 09:17
  • person is an ABRecordRef. – Rickster Jul 31 '15 at 21:04
12
(NSData*)ABPersonCopyImageDataWithFormat([targetPeople objectAtIndex:index], kABPersonImageFormatThumbnail)

This is faster since it returns a thumbnail.

Besi
  • 22,579
  • 24
  • 131
  • 223
ChangUZ
  • 5,380
  • 10
  • 46
  • 64
  • +1 because in addition to being a thumbnail it can be that the contact's image was cropped so ChangUZ's approach would return the same image that is shown in the address book. – Besi Jan 23 '12 at 14:02
  • 2
    But this method is available from iOS 4.1. – rowwingman Mar 31 '12 at 14:51
0

Slightly refreshed code:

UIImage *image = nil;

@try
{
    CFDataRef cfImage = ABPersonCopyImageData(person);
    // or CFDataRef cfImage = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
    if (cfImage)
    {
        image = [UIImage imageWithData:(__bridge NSData*)cfImage];
        CFRelease(cfImage);
    }
}
@catch (NSException *exception)
{
    //...
}
Rok Jarc
  • 18,765
  • 9
  • 69
  • 124