Android获取视频的第一帧照片

时间:2025-01-28 08:47:32
MediaMetadataRetriever mmr=new MediaMetadataRetriever();//实例化MediaMetadataRetriever对象 String path = videopath; File file=new File(path);//实例化File对象,文件路径为/storage/emulated/0/shipin.mp4 (手机根目录) if(!file.exists()){ // (, "文件不存在", Toast.LENGTH_SHORT).show(); } mmr.setDataSource(path); Bitmap bitmap = mmr.getFrameAtTime(0); //0表示首帧图片 mmr.release(); //释放MediaMetadataRetriever对象 if(bitmap!=null){ // (, "获取视频缩略图成功", 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.LENGTH_SHORT).show(); } catch (Exception e) { // (, "保存图片失败!" + ().toString(), Toast.LENGTH_LONG).show(); e.printStackTrace(); } }else{ // (, "获取视频缩略图失败", Toast.LENGTH_SHORT).show(); }