Получение растрового изображения из пути к файлу MediaStore.Audio.Albums.ALBUM_ART

ContentResolver contentResolver1 = getActivity().getContentResolver();
Uri uri1 = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
String[] projection1 = new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART};
String selection1 = MediaStore.Audio.Albums._ID + " = ?";
String[] selectionArgs1 = new String[]{String.valueOf(albumId)};  //albumId is MediaStore.Audio.Media.ALBUM_ID

Cursor cursor1 = contentResolver1.query(uri1, projection1, selection1, selectionArgs1, null);

if (cursor1 != null) {
   if (cursor1.moveToFirst()) {
       String albumPath = cursor1.getString(cursor1.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
       if (albumPath != null)
           albumArt = BitmapFactory.decodeFile(albumPath);          
   }
   cursor1.close();
}

BitmapFactory.decodeFile(albumPath) выдает исключение FileNotFoundException, хотя albumPath имеет следующее значение: /storage/emulated/0/Android/data/com.android.providers.media/albumthumbs/1502945757087

Комментарий к этому ответу говорит то же самое об использовании пути к файлу для получения растрового изображения из BitmapFactory.decodeFile(), который не работает в моем кейс. Как использовать указанный выше путь для получения растрового изображения?


person Darshan Miskin    schedule 17.08.2017    source источник
comment
каково ваше значение AlbumPath? это ноль?   -  person redAllocator    schedule 17.08.2017
comment
Нет. у него есть правильный путь, как указано в вопросе.   -  person Darshan Miskin    schedule 17.08.2017
comment
Вы должны запросить разрешение. Вам не нужно получать путь. пожалуйста, прочитайте его еще раз. Быстрый способ - понизить targetApi до 22 (файл build.gradle).   -  person redAllocator    schedule 17.08.2017


Ответы (3)


Попробуй это:

  Cursor cursor = getActivity().managedQuery(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, 
                    new String[] {MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART}, 
                    MediaStore.Audio.Albums._ID+ "=?", 
                    new String[] {String.valueOf(id_alnum)}, 
                    null);

    if (cursor.moveToFirst()) {
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
        //TODO code
    }
person Namrata    schedule 17.08.2017
comment
такой же. переменная path имеет путь, но BitmapFactory.decodeFile(path) дает исключение файл не найден. - person Darshan Miskin; 17.08.2017

В этом примере используется строка полного пути к вашему альбому.

     public static Bitmap decodeSampledBitmapFromFile(String picture, int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(picture, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(picture, options);
}


   public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

дополнительный пример, где вы используете uri (Источник: смузи Лукаса Роча):

    private Bitmap decodeSampledBitmapFromResource(Uri imageUri, int reqWidth,
        int reqHeight) {
    InputStream is = null;
    try {
        is = mContext.getContentResolver().openInputStream(imageUri);
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, null, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);
        options.inJustDecodeBounds = false;
        is = mContext.getContentResolver().openInputStream(imageUri);
        return BitmapFactory.decodeStream(is, null, options);
    } catch (FileNotFoundException e) {
   //     e.printStackTrace();
        return null;
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
    //      e.printStackTrace();
        }
    }
}
@Override
public Bitmap loadItem(Long id) {
    Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
    Uri imageUri = Uri.withAppendedPath(sArtworkUri, String.valueOf(id));
    Resources res = mContext.getResources();
    int width = res.getDimensionPixelSize(R.dimen.image_width);
    int height = res.getDimensionPixelSize(R.dimen.image_height);

    Bitmap bitmap = null;

    try {
        bitmap = decodeSampledBitmapFromResource(imageUri, width, height);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return bitmap;
}

например, поиск обложки альбома для трека с id = 3 с использованием метода uri:

imageUri = content://media/external/audio/albumart/3
sArtworkUri=content://media/external/audio/albumart
person Theo    schedule 19.08.2017
comment
Можете ли вы предоставить образец строки для полного пути к файлу? - person Darshan Miskin; 19.08.2017

Вы должны запросить разрешение. Вам не нужно получать путь. Пожалуйста, прочитайте это снова

Самый быстрый — понизить targetApi до 22 (файл build.gradle).

или используя новую модель запроса разрешения:

Запрос разрешений во время выполнения

person redAllocator    schedule 17.08.2017
comment
Как вообще связаны контакты и медиамагазин? - person Darshan Miskin; 17.08.2017
comment
вы должны проверить разрешение. пожалуйста, проверь это. - person redAllocator; 17.08.2017
comment
Вопрос не в доступе к внешнему хранилищу. Речь идет о получении растрового изображения из пути к файлу. - person Darshan Miskin; 17.08.2017
comment
Это не ответ, просто больше путаницы для человека, задающего вопрос. Я опубликую ответ завтра, так как сейчас поздно в Великобритании. - person Theo; 18.08.2017