最近整理了一下項目中使用的儲存本地圖檔縮略圖和視訊縮略圖的方法:
/* 得到本地的壓縮圖檔
*
* @param imagePath
* @param width
* @param height
* @return
*/
private Bitmap getImageThumbnail(String imagePath, int width, int height) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 擷取這個圖檔的寬和高,注意此處的bitmap為null
bitmap = BitmapFactory.decodeFile(imagePath, options);
options.inJustDecodeBounds = false; // 設為 false
// 計算縮放比
int h = options.outHeight;
int w = options.outWidth;
int beWidth = w / width;
int beHeight = h / height;
int be = 1;
if (beWidth < beHeight) {
be = beWidth;
} else {
be = beHeight;
}
if (be <= 0) {
be = 1;
}
options.inSampleSize = be;
// 重新讀入圖檔,讀取縮放後的bitmap,注意這次要把options.inJustDecodeBounds 設為 false
bitmap = BitmapFactory.decodeFile(imagePath, options);
// 利用ThumbnailUtils來建立縮略圖,這裡要指定要縮放哪個Bitmap對象
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
private Bitmap getVideoThumbnail(String videoPath, int width, int height,
int kind) {
Bitmap bitmap = null;
// 擷取視訊的縮略圖
bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
System.out.println("w" + bitmap.getWidth());
System.out.println("h" + bitmap.getHeight());
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}