阿里云如何获取视频的某一帧作为封面
在项目中,需要上传视频到阿里云,并把封面链接存入MYSQL数据库,封面需要从视频中截取一帧,那么如何截取呢???
/*
* @Author YangJiaWen
* @Description //用户上传视频
* @Date 10:38 2021/8/17
* @Param
* file file 视频文件
title string 标题
intro string 简介
category_id integer 分类ID
* @return
**/
@PostMapping("/user/videos")
@RequiredToken
public ResponseEntity<Video> uploadVideo(MultipartFile file,
String title,
String intro,
@RequestParam("category_id") Integer categoryId,
HttpServletRequest request) throws IOException {
//1.获取文件原始名称
String originalFilename = file.getOriginalFilename();
log.info("接收文件名称: {}", originalFilename);
log.info("类别id: {}", categoryId);
log.info("文件大小为: {}", file.getSize());
//2.获取文件后缀 mp4 avi ....
String ext = FilenameUtils.getExtension(originalFilename);
//3.生成uuid
String uuidFileName = UUID.randomUUID().toString().replace("-", "");
//4.生成uuid文件名名称
String newFileName = uuidFileName + "." + ext;
//5.上传到阿里云后返回url
String url = UploadVideoUtil.upload(file.getInputStream(), newFileName);
log.info("上传成功返回的地址: {}", url);
//6.获取视频封面
//阿里云oss截取视频中某一帧作为封面
String cover = url + "?x-oss-process=video/snapshot,t_30000,f_jpg,w_0,h_0,m_fast,ar_auto";
log.info("阿里云oss根据url截取视频封面: {}", cover);
Video video = new Video();
User user =(User) request.getAttribute("user");
//设置Video属性值
video.setUid(user.getId());
video.setTitle(title);
video.setIntro(intro);
video.setLink(url);
video.setCover(cover);
video.setCategoryId(categoryId);
video.setCreatedAt(new Date());
video.setUpdatedAt(new Date());
Video newVideo = videosClient.saveVideo(video);
ResponseEntity<Category> responseEntity = categoriesClient.selectOne(categoryId);
newVideo.setCategory(responseEntity.getBody().getName());
newVideo.setLikes(0);
return new ResponseEntity<>(newVideo,HttpStatus.OK);
}
public class UploadVideoUtil {
public static String upload(InputStream inputStream,String fileName){
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "xxxxxxxxxxxx";
String accessKeySecret = "xxxxxxxxxxxx";
String bucketName = "doublebili";
String url = "https://doublebili.oss-cn-hangzhou.aliyuncs.com/doublebiliVideo/";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
ossClient.putObject(bucketName, "doublebiliVideo/" + fileName, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//返回文件地址
return url + fileName;
}
}
前端
截取视频的一帧作为封面
String cover = url + "?x-oss-process=video/snapshot,t_30000,f_jpg,w_0,h_0,m_fast,ar_auto";
url为上传视频后返回的连接,只需要通过在链接后添加相应的参数即可,如下图
该url的含义是:从30s处截取,输出格式为jpg,宽度和高度随视频自适应,默认截图,自动旋转图片;