很多视频的第一个关键帧都是纯黑或纯白画面(如一些在YouTube下载的视频),那么我们在获取缩略图的时候,可以获取视频时长中间的关键帧,当然还是有一定几率会获取到纯黑纯白的画面(如时长中间的画面恰好就是纯黑),这个如果没有对画面进行检测,基本上是不可避免的,不算是bug。
public static Bitmap getVideoMiddleThumbnail(String path, int width, int height) {
float maxSize = Math.max(width, height);
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bitmap = null;
try {
retriever.setDataSource(path);
// 获取时长,单位:毫秒
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
// 取视频时长中点的最近一个关键帧
long frameTime = Long.parseLong(time) * 1000 / 2;
// 参数单位为微秒,1毫秒 = 1000微秒
bitmap = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
} 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.
}
}
if (bitmap == null) return null;
int tempWidth = bitmap.getWidth();
int tempHeight = bitmap.getHeight();
int max = Math.max(tempWidth, tempHeight);
if (max > maxSize) {
float scale = maxSize / max;
int w = Math.round(scale * tempWidth);
int h = Math.round(scale * tempHeight);
bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
}
return bitmap;
//return ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
}