Thumbnai结合MediaScanner快速获取图片缩略图

来源:互联网 发布:铁轨放石头知乎 编辑:程序博客网 时间:2024/05/16 12:28

1.启动MediaScanner服务,扫描媒体文件

扫描制定路径:

public void scanFileAsync(Context ctx, String filePath) {              Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);              scanIntent.setData(Uri.fromFile(new File(filePath)));              ctx.sendBroadcast(scanIntent);       }


 扫描全路径:

public static final String ACTION_MEDIA_SCANNER_SCAN_DIR = "android.intent.action.MEDIA_SCANNER_SCAN_DIR";       public void scanDirAsync(Context ctx, String dir) {              Intent scanIntent = new Intent(ACTION_MEDIA_SCANNER_SCAN_DIR);              scanIntent.setData(Uri.fromFile(new File(dir)));              ctx.sendBroadcast(scanIntent);       }

Thumbnails:MediaStore.Images.Thumbnails
获取图片的在MediaStore中存储的id
String[] projection2 = { "_id",}; Uri uri2 = MediaStore.Images.Media.getContentUri("external"); String where = String.format( "_data = '%s' ", file_path); Cursor c2 = Media.query(getContentResolver(), uri2, projection2, where , null); long image_id = c2.getLong(c2.getColumnIndexOrThrow("_id")); 
根据id获得thumbnails的缩略图:
String[] projection = { "MediaStore.Images.Thumbnails.DATA"};
Cursor c = Thumbnails.queryMiniThumbnail(getContentResolver(), image_id,Thumbnails.MINI_KIND, projection); thumbnail_path = c.getString(c.getColumnIndexOrThrow("_data")); 


ThumbnailUtils,这是一个工具类,快速生成缩略图

static Bitmap createVideoThumbnail(String filePath, int kind)
Create a video thumbnail for a video.

static Bitmap extractThumbnail(Bitmap source, int width, int height, int options)
Creates a centered bitmap of the desired size.

static Bitmap extractThumbnail(Bitmap source, int width, int height)
Creates a centered bitmap of the desired size.