Last active
November 17, 2016 20:51
-
-
Save shakdwipeea/2e94fd7394a65df6ddac33dbc230b748 to your computer and use it in GitHub Desktop.
Load a contact photo thumbnail and return it as a Bitmap, resizing the image to the provided image dimensions as needed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @param photoData photo ID Prior to Honeycomb, the contact's _ID value. | |
* For Honeycomb and later, the value of PHOTO_THUMBNAIL_URI. | |
* @return A thumbnail Bitmap, sized to the provided width and height. | |
* Returns null if the thumbnail is not found. | |
*/ | |
private Bitmap loadContactPhotoThumbnail(String photoData) { | |
// Creates an asset file descriptor for the thumbnail file. | |
AssetFileDescriptor afd = null; | |
// try-catch block for file not found | |
try { | |
// Creates a holder for the URI. | |
Uri thumbUri; | |
// If Android 3.0 or later | |
if (Build.VERSION.SDK_INT | |
>= | |
Build.VERSION_CODES.HONEYCOMB) { | |
// Sets the URI from the incoming PHOTO_THUMBNAIL_URI | |
thumbUri = Uri.parse(photoData); | |
} else { | |
// Prior to Android 3.0, constructs a photo Uri using _ID | |
/* | |
* Creates a contact URI from the Contacts content URI | |
* incoming photoData (_ID) | |
*/ | |
final Uri contactUri = Uri.withAppendedPath( | |
ContactsContract.Contacts.CONTENT_URI, photoData); | |
/* | |
* Creates a photo URI by appending the content URI of | |
* Contacts.Photo. | |
*/ | |
thumbUri = | |
Uri.withAppendedPath( | |
contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY); | |
} | |
/* | |
* Retrieves an AssetFileDescriptor object for the thumbnail | |
* URI | |
* using ContentResolver.openAssetFileDescriptor | |
*/ | |
afd = getContentResolver(). | |
openAssetFileDescriptor(thumbUri, "r"); | |
/* | |
* Gets a file descriptor from the asset file descriptor. | |
* This object can be used across processes. | |
*/ | |
FileDescriptor fileDescriptor = afd.getFileDescriptor(); | |
// Decode the photo file and return the result as a Bitmap | |
// If the file descriptor is valid | |
if (fileDescriptor != null) { | |
// Decodes the bitmap | |
return BitmapFactory.decodeFileDescriptor( | |
fileDescriptor, null, null); | |
} | |
// If the file isn't found | |
} catch (FileNotFoundException e) { | |
/* | |
* Handle file not found errors | |
*/ | |
// In all cases, close the asset file descriptor | |
} finally { | |
if (afd != null) { | |
try { | |
afd.close(); | |
} catch (IOException e) {} | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment