天天看點

android 封面,Android加載視訊封面的兩種方式

packagecom.z.z.utils;

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;

}

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);

}

}

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);

}

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;

}

}