1.本地视频
MediaMetadataRetriever media = new MediaMetadataRetriever();
media.setDataSource(videoPath);
Bitmap bitmap = media.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
ivAddPhoto.setImageBitmap(bitmap);
2.网络视频
public static Bitmap createVideoThumbnail(String filePath, int kind)
{
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try
{
if (filePath.startsWith("http://")
|| filePath.startsWith("https://")
|| filePath.startsWith("widevine://"))
{
retriever.setDataSource(filePath, new Hashtable<String, String>());
}
else
{
retriever.setDataSource(filePath);
}
bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
}
catch (IllegalArgumentException ex)
{
ex.printStackTrace();
}
catch (RuntimeException ex)
{
ex.printStackTrace();
}
finally
{
try
{
retriever.release();
}
catch (RuntimeException ex)
{
ex.printStackTrace();
}
}
if (bitmap == null)
{
return null;
}
if (kind == MediaStore.Images.Thumbnails.MINI_KIND)
{
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int max = Math.max(width, height);
if (max > 512)
{
float scale = 512f / max;
int w = Math.round(scale * width);
int h = Math.round(scale * height);
bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
}
}
else if (kind == MediaStore.Images.Thumbnails.MICRO_KIND)
{
bitmap = ThumbnailUtils.extractThumbnail(bitmap,
96,
96,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
}
return bitmap;
}
mIvBigShow.setImageBitmap(createVideoThumbnail(videoPath,MediaStore.Images.Thumbnails.MINI_KIND));
3.使用Glide获取视频第一帧
public static void loadCover(ImageView imageView, String url, Context context) {
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Glide.with(context)
.setDefaultRequestOptions(
new RequestOptions()
.frame(4000000)
.centerCrop()
.error(R.mipmap.eeeee)
.placeholder(R.mipmap.ppppp)
)
.load(url)
.into(imageView);
}