从iPhone通讯录中获取一个人的图像

17

如何从iPhone通讯录中获取一个人的头像?

3个回答

42

你可以这样做...

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

UIImage  *img = [UIImage imageWithData:imgData];

其中 person 的类型为 ABRecordRef。由于CFData和NSData是toll-free bridged,你可以直接将CFData强制转换为NSData并获取图像。

希望这能有所帮助。


请注意代码片段最后一行中的 "imgaeWithData:imgData" 应更正为 "imageWithData:imgData"。我已经修复了。 - Peter Johnson
请注意,这可能不是用户所期望的图像,因为它不是图像的裁剪版本。请参考ChangUZ的答案 - Besi
但是,在不提及任何图像格式的情况下更有优势,因为在将图像填充到表视图单元格中时,我们使用图像视图作为附件视图,因为它会自动调整图像大小并将每个图像设置为独特的格式(相同尺寸)。 :) - Eshwar Chaitanya
person 是一个 ABRecordRef。 - Rickster

12
(NSData*)ABPersonCopyImageDataWithFormat([targetPeople objectAtIndex:index], kABPersonImageFormatThumbnail)

这样更快,因为它返回了一个缩略图。


+1 是因为除了作为缩略图之外,联系人的图像可能已经被裁剪,所以 ChangUZ 的方法会返回与通讯录中显示的相同的图像。 - Besi
2
但是这种方法仅适用于iOS 4.1及以上版本。 - rowwingman

0
稍微修改了代码:
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)
{
    //...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接