14

I have a String URL pointing to an image stored on the external storage of my device:

String imageUrl = "/storage/emulated/0/DCIM/100MEDIA/IMAG0823.jpg"

I want to get query the MediaStore to get the thumbnail for this image. This is what I do right now:

private String getImageThumbnailPath(Context ctx, String imageUrl){

    Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnails(
            ctx.getContentResolver(), Uri.fromFile(new File(imageUrl)),
            MediaStore.Images.Thumbnails.MICRO_KIND,
            null);

    String url = "";
    if( cursor != null && cursor.getCount() > 0 ) {
        cursor.moveToFirst();
        url = cursor.getString( cursor.getColumnIndex( MediaStore.Images.Thumbnails.DATA ) );
        cursor.close();
    }
    return url;
} 

However, calling this method and printing it's content shows nothing (the cursor is empty).

How do I query the MediaStore for the thumbnail url associated with my image URL?

Edit

I've also tried to parse the Uri directly from the image URL, as so:

Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnails(
        ctx.getContentResolver(), Uri.parse(imageUrl),
        MediaStore.Images.Thumbnails.MINI_KIND,
        null);

But the result is the same.

6
  • Check Uri value Uri.fromFile(new File(imageUrl))
    – dieter_h
    Aug 15, 2015 at 20:42
  • it is /storage/emulated/0/DCIM/100MEDIA/IMAG0823.jpg @dieter_h
    – Marcus
    Aug 15, 2015 at 20:43
  • 3
    Should be file:///storage/emulated/0/DCIM/100MEDIA/IMAG0823.jpg
    – dieter_h
    Aug 15, 2015 at 20:46
  • Sorry, ignore that last comment. The output from System.out.println(Uri.fromFile(new File(imageUrl))); is file:///storage/emulated/0/DCIM/100MEDIA/IMAG0823.jpg
    – Marcus
    Aug 15, 2015 at 20:57
  • Have you found solution? Feb 20, 2017 at 16:07

4 Answers 4

7
+25

Following code works if you have pick image from gallery, otherwise we can not have thumbnail, and we have to create thumbnail.

First you have to find the MediaStore.Images.Media._ID

public String[] getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA,
            MediaStore.Images.Media._ID };
    Cursor cursor = getActivity().getContentResolver().query(contentUri,
            proj, null, null, null);
    int path_index = cursor.getColumnIndexOrThrow(proj[0]);
    int id_index = cursor.getColumnIndexOrThrow(proj[1]);
    cursor.moveToFirst();
    return new String[] { cursor.getString(path_index),
            cursor.getLong(id_index) + "" };
}

From above getRealPathFromURI now we have MediaStore.Images.Media._ID, use this id to find thumbnail.

public static Bitmap getThumbnail(ContentResolver contentResolver, long id) {
        Cursor cursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media.DATA}, // Which columns
                // to return
                MediaStore.Images.Media._ID + "=?", // Which rows to return
                new String[]{String.valueOf(id)}, // Selection arguments
                null);// order

        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            String filePath = cursor.getString(0);
            cursor.close();
            int rotation = 0;
            try {
                ExifInterface exifInterface = new ExifInterface(filePath);
                int exifRotation = exifInterface.getAttributeInt(
                        ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
                if (exifRotation != ExifInterface.ORIENTATION_UNDEFINED) {
                    switch (exifRotation) {
                        case ExifInterface.ORIENTATION_ROTATE_180:
                            rotation = 180;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_270:
                            rotation = 270;
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_90:
                            rotation = 90;
                            break;
                    }
                }
            } catch (IOException e) {
                Log.e("getThumbnail", e.toString());
            }
            Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
                    contentResolver, id,
                    MediaStore.Images.Thumbnails.MINI_KIND, null);
            if (rotation != 0) {
                Matrix matrix = new Matrix();
                matrix.setRotate(rotation);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                        bitmap.getHeight(), matrix, true);
            }
            return bitmap;
        } else
            return null;
    }

To use above LOC

Updated

String[] imageInfo = getRealPathFromURI(Uri.parse("YOUR_IMAGE_PATH"));
yourImageView.setImageBitmap(getThumbnail(getActivity()
                    .getContentResolver(), Long.parseLong(imageInfo[1])));

Uri.parse("YOUR_IMAGE_PATH") is contentUri

3
  • What's contentUri in the first method?
    – Marcus
    Aug 22, 2015 at 10:02
  • In getRealPathFromURI method, getActivity().getContentResolver().query(contentUri, proj, null, null, null); returns null. My contentUri is /storage/emulated/0/DCIM/100MEDIA/IMAG0827.jpg. Any idea?
    – Marcus
    Aug 24, 2015 at 17:20
  • I know it's been 4 years sine you posted this response but I'm having problem with MediaStore.Images.Thumbnails.getThumbnail method. It returns null for some reason. I stepped thorough my code and I can see query returns proper cursor, and I could extract image_id from it.
    – KMC
    Oct 24, 2019 at 2:38
2

I am sure the ThumbnailUtils class can help you on this.

Bitmap thumb = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath), THUMBSIZE, THUMBSIZE);

It returns a Bitmap and yous should check if it not null before using it. Sometimes, corrupted files return null thumbnails.

If you are not supporting anything below API level 8, you should be using this.

UPDATE

If you need the thumbnail path, please use this method,

public String getThumbnailPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media._ID };
    String result = null;
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media._ID);

    cursor.moveToFirst();
    long imageId = cursor.getLong(column_index);
    cursor.close();

    cursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(
            getContentResolver(), imageId,
            MediaStore.Images.Thumbnails.MINI_KIND,
            null);
    if (cursor != null && cursor.getCount() > 0) {
        cursor.moveToFirst();
        result = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
        cursor.close();
    }
    return result;
}
8
  • I might have been vague in my question, but I want the url of the bitmap, which is stored in the MediaStore database
    – Marcus
    Aug 18, 2015 at 5:43
  • Its working perfectly for you. I think you should try with it first. Let me know if it works.
    – Aritra Roy
    Aug 19, 2015 at 8:17
  • I tried it, managedQuery is deprecated. I used contentResolver.query() instead, but it returned null.
    – Marcus
    Aug 19, 2015 at 10:32
  • Thre's a reason for it being deprecated tho, is it not?
    – Marcus
    Aug 19, 2015 at 10:34
  • That's not the scope of this answer. If you can try it and confirm its not working, I can try to help you in other way. But I won't be able to help, if you are not ready to cooperate. Thanks.
    – Aritra Roy
    Aug 19, 2015 at 10:36
0

you can use this method to resize and save thumbnail behind original image :

private void resizer(String local_path, int original_image_w, int original_image_h){
    if(local_path.length() > 0){
        int imgW = (int) (original_image_w * 0.10); // Can Change By Device Width
        int imgH = (int) (original_image_h * 0.10); // Can Change By Device height
        Log.d("TAG_RESIZE", "Resizer, W : "+imgW+" , H : "+imgH);
        Log.d("TAG_RESIZE", "Resizer local path : "+(new File(local_path).exists() ? "Exist" : "Not Exist")+" , \n"+local_path);
        String ex = local_path.substring(local_path.lastIndexOf('.')+1, local_path.length());
        // ExceptionHelpers.eLog(G.Logs.Error, "Slider Downloader Image ex : " + ex);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap dlBitmap = BitmapFactory.decodeFile(local_path, options);
        Bitmap resized = Bitmap.createScaledBitmap(dlBitmap, imgW, imgH, true);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(local_path.replace("."+ex, "_thumb."+ex));
            if(ex.toLowerCase().startsWith("jpg") || ex.toLowerCase().startsWith("jpeg")){
                resized.compress(Bitmap.CompressFormat.JPEG,100, fos);
            }else if(ex.toLowerCase().startsWith("png")){
                resized.compress(Bitmap.CompressFormat.PNG,100, fos);
            }

            fos.flush();
            fos.close();

        } catch (Exception e) {
            ExceptionHelpers.catchMessage(e); // My Custom Class To Log Errors, Useful To Save Error Logs And Send To Server
        }
    }
}

Also it will capture Memory Storage, But Faster than RunTime resize

2
  • 1
    This is what Bitmap thumb = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath), THUMBSIZE, THUMBSIZE); does, why reinvent the wheel? Also, it's not what I asked for.
    – Marcus
    Aug 18, 2015 at 11:06
  • @Marcus told you reasone of use it Aug 25, 2015 at 4:40
-2

You have pick an image from gallery, otherwise we can not have thumbnail. You can first launch a intent to pick an image from gallery like this.

Intent galleryIntent = new Intent(Intent.ACTION_PICK, 
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    galleryIntent.setType("image/*");
                    startActivityForResult(galleryIntent, REQUEST_PICK_FROM_GALLERY);

after this in your onActivityResult do this

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_PICK_FROM_GALLERY:
            Bitmap thumbnail = new File(intent.getExtras().get("data"));
                    break;
            }
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.