一、获取从相册选择视频的第一帧作为封面图,并保存到相册,返回封面图在相册中的路径
/**
* 从相册选择的视频,截取第一帧获取其封面图保存到相册,并返回封面图的路径
* @param context
* @param videoPath 视频路径 类似这种:/storage/emulated/0/Android/data/包名/files/Movies/1714386774161.mp4
* @return 返回截取的视频封面图在相册中的路径地址
*/
private String extractAndSaveCover(Context context, String videoPath){
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
// 设置视频源路径
retriever.setDataSource(videoPath);
// 获取视频第一帧的Bitmap
Bitmap firstFrame = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
if (firstFrame != null) {
// 生成保存图片的文件名,格式为当前日期时间
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "VIDEO_THUMB_" + timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = new File(storageDir, imageFileName);
// 将Bitmap保存到图片文件
FileOutputStream out = null;
try {
out = new FileOutputStream(image);
firstFrame.compress(Bitmap.CompressFormat.JPEG, 100, out); // 压缩质量100%,可根据需要调整
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 将图片加入系统相册,以便用户在相册中查看
galleryAddPic(context, image.getAbsolutePath());
return image.getAbsolutePath(); // 返回图片在相册中的地址
} else {
Log.e("VideoThumbnailExtractor", "Failed to get the first frame.");
return "";
}
} finally {
retriever.release(); // 释放资源
}
}
private void galleryAddPic(Context context, String filePath) {
// 通知系统图库更新
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(filePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}