利用ThumbnailUtils來實現獲取圖片和視頻的縮略圖
獲取圖片縮略圖
利用ThumbnailUtils的extractThumbnail()方法來實現
1. static Bitmap extractThumbnail(Bitmap source, int width, int height, int options)
//直接對Bitmap進行縮略操作,最後一個參數定義爲OPTIONS_RECYCLE_INPUT ,來回收資源
2. static Bitmap extractThumbnail(Bitmap source, int width, int height)
// 這個和上面的方法一樣,無options選項
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;
}
獲取視頻的縮略圖
- static Bitmap createVideoThumbnail(String filePath, int kind)
//獲取視頻文件的縮略圖,第一個參數爲視頻文件的位置,比如/sdcard/android123.3gp,而第二個參數可以爲MINI_KIND或 MICRO_KIND最終和分辨率有關
public static Bitmap getVideoThumbnail(String filePath, int width_, int height_, int kind) {
Bitmap bitmap = null;
try {
bitmap = ThumbnailUtils.createVideoThumbnail(filePath,kind);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width_, height_,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
} catch (Exception e) {
e.printStackTrace();
}
if (bitmap == null) return null;
return bitmap;
}
項目源碼地址
CSDN:
GitHub: