1、Video
對于視頻,取第一幀作為縮略圖,也就是怎樣從filePath得到一個Bitmap對象。
private Bitmap createVideoThumbnail(String filePath) {
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
retriever.setDataSource(filePath);
bitmap = retriever.captureFrame();
} catch(IllegalArgumentException ex) {
// Assume this is a corrupt video file
} catch (RuntimeException ex) {
// Assume this is a corrupt video file.
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
// Ignore failures while cleaning up.
}
}
return bitmap;
}
Android提供了MediaMetadataRetriever,由JNI(media_jni)實現。
看得出MediaMetadataRetriever主要有兩個功能:MODE_GET_METADATA_ONLY和MODE_CAPTURE_FRAME_ONLY
這里設mode為MODE_CAPTURE_FRAME_ONLY,調用captureFrame取得一幀。
另外還有兩個方法可以用:
extractMetadata 提取文件信息,ARTIST、DATE、YEAR、DURATION、RATING、FRAME_RATE、VIDEO_FORMAT
和extractAlbumArt 提取專輯信息,這個下面的音樂文件可以用到。
2、Music
對于音樂,取得AlbumImage作為縮略圖,還是用MediaMetadataRetriever
private Bitmap createAlbumThumbnail(String filePath) {
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY);
retriever.setDataSource(filePath);
byte[] art = retriever.extractAlbumArt();
bitmap = BitmapFactory.decodeByteArray(art, 0, art.length);
} catch(IllegalArgumentException ex) {
} catch (RuntimeException ex) {
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
// Ignore failures while cleaning up.
}
}
return bitmap;
}
retriever.extractAlbumArt()得到的是byte數組,還需要一步用BitmapFactory編碼得到Bitmap對象。
3、Image
圖片就很簡單了
Bitmap bm = null;
Options op = new Options();
op.inSampleSize = inSampleSize;
op.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(mFile.getPath(), op);
能直接得到Bitmap對象,把圖片縮小到合適大小就OK。
同樣上面的Video和Music,retrive到Bitmap后也需要縮小處理。
