android获取存储在路径已知的SD卡上的图像缩略图

pan*_*wal 17 android thumbnails

说我在路径上有一个图像存储"/mnt/images/abc.jpg".如何为此图像获取系统生成的缩略图位图.我知道如何从其Uri获取图像的缩略图,但不知道如何从其文件路径获取图像的缩略图

agi*_*llo 24

你可以尝试这个:

public static Bitmap getThumbnail(ContentResolver cr, String path) throws Exception {

    Cursor ca = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null);
    if (ca != null && ca.moveToFirst()) {
        int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
        ca.close();
        return MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MICRO_KIND, null );
    }

    ca.close();
    return null;

}
Run Code Online (Sandbox Code Playgroud)


Can*_*ner 4

Uri您可以从这样的文件中获取:

Uri uri = Uri.fromFile(new File("/mnt/images/abc.jpg"));
Bitmap thumbnail = getPreview(uri);
Run Code Online (Sandbox Code Playgroud)

以下函数为您提供缩略图:

Bitmap getPreview(Uri uri) {
    File image = new File(uri.getPath());

    BitmapFactory.Options bounds = new BitmapFactory.Options();
    bounds.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(image.getPath(), bounds);
    if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
        return null;

    int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
            : bounds.outWidth;

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
    return BitmapFactory.decodeFile(image.getPath(), opts);     
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为使用 MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), Long.parseLong(_imageUri.getLastPathSegment()), type, null);` 将是一个更好的选择,因为系统大多数时候都会缓存缩略图 (8认同)
  • 您获取 uri 的方法似乎无法正常工作,因为对于路径为“/mnt/sdcard/2011-12-02 11.22.50.jpg”的文件,实际的 uri 是 ontent://media/external/images/media /556 其中 Uri.fromFile(...) 方法返回 file:///mnt/sdcard/2011-12-02%2011.22.50.jpg (2认同)