Get thumbnail URL from image URL

2020-07-03 04:59发布

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.

标签: android
4条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-03 05:05

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

查看更多
Evening l夕情丶
3楼-- · 2020-07-03 05:09

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

查看更多
Root(大扎)
4楼-- · 2020-07-03 05:15

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;
            }
        }
    }
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-07-03 05:26

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;
}
查看更多
登录 后发表回答