android 封面,Android加载视频封面的两种方式

  • Post author:
  • Post category:其他


packagecom.z.z.utils;/** :Created by z on 2020-08-31*/

importandroid.content.Context;importandroid.graphics.Bitmap;importandroid.media.MediaMetadataRetriever;importandroid.util.Log;importandroid.widget.ImageView;importandroidx.annotation.NonNull;importcom.bumptech.glide.Glide;importcom.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;importcom.bumptech.glide.load.resource.bitmap.BitmapTransformation;importcom.bumptech.glide.load.resource.bitmap.VideoDecoder;importcom.bumptech.glide.request.RequestOptions;importjava.security.MessageDigest;importjava.util.HashMap;public classVideoFrameTool {private staticVideoFrameTool instance;public staticVideoFrameTool getInstance() {if (instance == null) {

instance= newVideoFrameTool();

}returninstance;

}/*** 获取网络视频第一帧

*

*@paramvideoUrl

*@return

*/

public voidloadFirst(String videoUrl, @NonNull ImageView cover) {

Bitmap bitmap= null;

MediaMetadataRetriever retriever= newMediaMetadataRetriever();try{//根据url获取缩略图

retriever.setDataSource(videoUrl, newHashMap());//获得第一帧图片

bitmap =retriever.getFrameAtTime();

}catch(IllegalArgumentException e) {//e.printStackTrace();

Log.e(“zhu”, e.toString());

}finally{

retriever.release();

}if (bitmap != null) {

cover.setImageBitmap(bitmap);

}

}/***   context 上下文

*   uri 视频地址

*   imageView 设置image

*   frameTimeMicros 获取某一时间帧*/

public void loadFirstWithGlide(final Context context, String uri, ImageView imageView, longframeTimeMicros) {

RequestOptions requestOptions=RequestOptions.frameOf(frameTimeMicros);

requestOptions.set(VideoDecoder.FRAME_OPTION, MediaMetadataRetriever.OPTION_CLOSEST);

requestOptions.transform(newBitmapTransformation() {

@Overrideprotected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, intoutHeight) {returntoTransform;

}

@Overridepublic voidupdateDiskCacheKey(MessageDigest messageDigest) {try{

messageDigest.update((context.getPackageName()+ “RotateTransform”).getBytes(“utf-8”));

}catch(Exception e) {

e.printStackTrace();

}

}

});

Glide.with(context).load(uri).apply(requestOptions).into(imageView);

}/*** 获取本地视频的第一帧

*

*@paramlocalPath

*@return

*/

publicBitmap getLocalVideoBitmap(String localPath) {

Bitmap bitmap= null;

MediaMetadataRetriever retriever= newMediaMetadataRetriever();try{//根据文件路径获取缩略图

retriever.setDataSource(localPath);//获得第一帧图片

bitmap =retriever.getFrameAtTime();

}catch(IllegalArgumentException e) {

e.printStackTrace();

}finally{

retriever.release();

}returnbitmap;

}

}