Android gets the first frame photo of the video

Android gets the first frame of photo after recording the video (video)

1. Application scenarios

After you have finished recording a video, or you already have a video, you need to display the cover when displaying, but the cover display requires pictures. At this time, you need to start getting the first frame of pictures from the video.

2. Code implementation
 MediaMetadataRetriever mmr=new MediaMetadataRetriever();//实例化MediaMetadataRetriever对象
        String path = videopath;
        File file=new File(path);//实例化File对象,文件路径为/storage/emulated/0/shipin.mp4 (手机根目录)
        if(!file.exists()){
    
    
//            Toast.makeText(SubmitVideoActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
        }
        mmr.setDataSource(path);
        Bitmap bitmap = mmr.getFrameAtTime(0);  //0表示首帧图片
        mmr.release(); //释放MediaMetadataRetriever对象
        if(bitmap!=null){
    
    
//            Toast.makeText(SubmitVideoActivity.this, "获取视频缩略图成功", Toast.LENGTH_SHORT).show();
            //存储媒体已经挂载,并且挂载点可读/写。
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    
    
                bitmap.recycle(); //回收bitmap
                return;
            }
            try {
    
    
                Calendar now = new GregorianCalendar();
                SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
                String picture_Name = simpleDate.format(now.getTime()); //获取当前时间戳作为文件名称,避免同名

                String framePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + Environment.DIRECTORY_DCIM
                        + File.separator + "visiontalk/pictures/"; //图片保存文件夹
                File frame_file = new File(framePath);
                if (!frame_file.exists()) {
    
    
                    frame_file.mkdirs();
                }
                File picture_file = new File(framePath,picture_Name + ".jpg"); // 创建路径和文件名的File对象
                FileOutputStream out = new FileOutputStream(picture_file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();   //注意关闭文件流
                fastPhoto=picture_file;
                Log.d("takeRec", "takeRec: "+picture_file);
//                Toast.makeText(SubmitVideoActivity.this, "保存图片成功!", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
    
    
//                Toast.makeText(SubmitVideoActivity.this, "保存图片失败!" + e.getMessage().toString(), Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }else{
    
    
//            Toast.makeText(SubmitVideoActivity.this, "获取视频缩略图失败", Toast.LENGTH_SHORT).show();
        }

In this, you must ensure that the path of the file is correct. If it is not correct, it will fail. Is it very simple?

Guess you like

Origin blog.csdn.net/wzx311/article/details/126276760