简体   繁体   English

如何从联系人获取照片?

[英]how to get photo from contacts?

I want to get photo from contacts, if some contacts don't have photo to return default photo(just silhouette), how can I do that? 我想从联系人中获取照片,如果某些联系人没有照片以返回默认照片(只是轮廓),该怎么办? Thanks in advance, Wolf. 预先感谢狼。

You can use ContactsContract.Contacts.Photo to get the picture for the specified contact. 您可以使用ContactsContract.Contacts.Photo来获取指定联系人的图片。

Full example from the above documentation link: 来自上述文档链接的完整示例:

public InputStream openDisplayPhoto(long contactId) {
     Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
     Uri displayPhotoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.DISPLAY_PHOTO);
     try {
         AssetFileDescriptor fd =
             getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
         return fd.createInputStream();
     } catch (IOException e) {
         return null;
     }
 }
public Uri getPhotoUri() {
    try {
        Cursor cur = this.ctx.getContentResolver().query(
                ContactsContract.Data.CONTENT_URI,
                null,
                ContactsContract.Data.CONTACT_ID + "=" + this.getId() + " AND "
                        + ContactsContract.Data.MIMETYPE + "='"
                        + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
                null);
        if (cur != null) {
            if (!cur.moveToFirst()) {
                return null; // no photo
            }
        } else {
            return null; // error in cursor process
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
            .parseLong(getId()));
    return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}

you can use it as 您可以将其用作

Uri u = objItem.getPhotoUri();
if (u != null) {
        mPhotoView.setImageURI(u);
} else {
        mPhotoView.setImageResource(R.drawable.ic_contact_picture_2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM