Reputation: 2092
When a contact has a connection, like Whatsapp or Skype, and that contact hasn't a photo, the Whatsapp or Skype photo appears.
How obtain the connection photo if the contact photo hasn't a photo?
public byte[] getPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
try
{
Cursor c = getContentResolver().query(photoUri,
new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
try {
if (c.moveToFirst()) {
final byte[] image = c.getBlob(0);
final Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
c.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return new byte[0];
}
SOLVED
This method works correctly. The problem was in another part of the program. Sorry for the inconvenience and thank you to all.
Upvotes: 1
Views: 95
Reputation: 28179
First, note that a Whatsapp
photo does not appear in your Contacts
app, it only appears within the Whatsapp
app, that's because it's a proprietary photo stored locally in the Whatsapp
app and is not accessible to 3rd party apps.
I'm not sure about Skype
, but if you do see a photo in the Contacts
app, you should be able to access it via the API.
The code you've posted accessed the thumbnail-sized photo of the contact, it's possible that the contact has only a high-res photo and no thumbnail.
Try this code using ContactsContract.DisplayPhoto:
public InputStream openDisplayPhoto(long photoFileId) {
Uri displayPhotoUri = ContentUris.withAppendedId(DisplayPhoto.CONTENT_URI, photoKey);
try {
AssetFileDescriptor fd = getContentResolver().openAssetFileDescriptor(
displayPhotoUri, "r");
return fd.createInputStream();
} catch (IOException e) {
return null;
}
}
Also, this code will show you all photos stored for a contact, along with their RawContact
ID source:
String[] projection = new String[] { CommonDataKinds.Photo.PHOTO_FILE_ID, CommonDataKinds.Photo.PHOTO, CommonDataKinds.Photo.RAW_CONTACT_ID };
String selection = Data.MIMETYPE + "='" + CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "' AND " + Data.CONTACT_ID + "=" + contactId;
Cursor c = resolver.query(Data.CONTENT_URI, projection, selection, null, null);
while (c != null && c.moveToNext()) {
Long photoId = c.getLong(0);
boolean hasPhoto = c.isNull(1);
Long rawContactId = c.getLong(2);
Log.d(TAG, "found photo: " + photoId + ", " + rawContactId + ", " + hasPhoto);
}
Upvotes: 1