Reputation: 71
As far as I can understand the right way of working with images in Android is to store images Uri in the database, not the image actual path. Thats how we can get thumbnails for free. And we don't need to prepare them by ourself and hide somewere. The code below takes thumbnails by Uri. Code works on android 4.4 and below. But to get image id it doesn't query content provider. It takes ID from Uri itself. The question is: Is it a stable solution, can I rely on it?
@TargetApi(Build.VERSION_CODES.KITKAT)
public static Bitmap getImageThumbnail(Context context, Uri uri){
final ContentResolver resolver = context.getContentResolver();
long id;
try {
if (UIUtils.hasKitKat() && DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
id = Long.parseLong(wholeID.split(":")[1]);
}
else if (isMediaUri(uri)){
id = ContentUris.parseId(uri);
}
else return null;
return MediaStore.Images.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
}
catch (Exception e) {
if (DEBUG) Log.e(TAG, "getThumbnail", e);
return null;
}
}
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
Upvotes: 2
Views: 977
Reputation: 9615
you should be using DocumentsContract.getDocumentThumbnail(). this is guaranteed to work with any document uri, not just the builtin media provider.
Upvotes: 3