调用ffmpeg视频压缩工具类
package com.example.demo; import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import it.sauronsoftware.jave.*;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import java.io.*;
import java.util.*; /**
* @Auther: xiyou
* @Date: 2019/4/11 15:40
* @Description:
*/
@Component
public class Util { private static Logger logger = LoggerFactory.getLogger(Util.class); @Value("${endpoint}") private String endpoint; @Value("${accessId}") private String accessId; @Value("${accessKey}") private String accessKey; @Value("${bucket}") private String bucket; @Value("${host}") private String host; @Value("${callbackUrl}") private String callbackUrl; @Value("${dir}") private String dir; //Windows下 ffmpeg.exe的路径
private static String ffmpegEXE = "D:/ffmpeg/bin/ffmpeg.exe"; //Linux与mac下 ffmpeg的路径
//private static String ffmpegEXE = "/developer/ffmpeg-4.0/bin/ffmpeg"; // 图片类型数组
public String[] arrImage = { "bmp", "jpg", "png", "jpeg" };
// 视频类型数组
public String[] arrVideo = { "mp4", "mov", "3gp" }; /**
* 压缩图片
*/
public void zipPic(MultipartFile file, String proFileName, String suffixName) throws Exception {
Thumbnails.of(file.getInputStream()) // 文件流或者文件 或者文件数组
.scale(0.5) // 缩放比
.outputFormat(suffixName) // 输出格式
.outputQuality(0.8) // 输出质量
.toFile(proFileName); // 输出文件
} /**
* 删除文件
*/
public void delFile(String fileName) {
File deFile = new File(fileName);
if (deFile.exists()) {
deFile.delete();
}
} /**
* 压缩视频
*/
public void zipVideo(MultipartFile file, String proFileName, String suffixName) throws IOException {
String fileName = getFileName(file);
File source = new File(fileName);
File target = new File(proFileName + "." + suffixName);
try {
// 音频编码设置
AudioAttributes audio = new AudioAttributes();
audio.setCodec("libmp3lame");
audio.setBitRate(new Integer(64000));
audio.setChannels(new Integer(1));
audio.setSamplingRate(new Integer(22050)); // 视频编码设置
VideoAttributes video = new VideoAttributes();
video.setCodec("mpeg4");
video.setBitRate(new Integer(160000));
video.setFrameRate(new Integer(15));
// video.setSize(new VideoSize(100, 150)); // 视频转码编码设置
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat(suffixName);
attrs.setAudioAttributes(audio);
attrs.setVideoAttributes(video); // 编码器
Encoder encoder = new Encoder();
encoder.encode(source, target, attrs);
} catch (EncoderException e) {
e.printStackTrace();
}
} /**
* MultipartFile 转 File
*/
public void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 判断图片类型
*/
public boolean JudgeFileType(String[] arr, String targetValue) {
return Arrays.asList(arr).contains(targetValue);
} /**
* MultipartFile 转 File 获取文件名称
*/
public String getFileName(MultipartFile file) throws IOException {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return String.valueOf(toFile);
} /***
* 活体视频验证返回信息
* @param line
* @return
*/
public CommonResult identityResultInfo(String line) {
CommonResult result = new CommonResult();
JSONObject json = JSONObject.parseObject(line);
String code = json.getString("code");
String message = json.getString("message");
String passed = json.getString("passed");
Object liveness_score = json.get("liveness_score");
Double verification_score = json.getDouble("verification_score");
Object image_id = json.get("image_id");
Object image_timestamp = json.get("image_timestamp");
Object base64_image = json.get("base64_image");
Object request_id = json.get("request_id");
if ("true".equals(passed) && "1000".equals(code)) {
if (rangeInDefined(verification_score)) {
result.setResultCode(code);
result.setResultMsg(passed);
result.setModel("活体验证成功,人脸比对得分通过");
} else {
result.setResultCode("1001");
result.setResultMsg("false");
result.setModel("人脸比对得分不通过");
}
} else {
result.setResultCode(code);
result.setResultMsg(message);
result.setModel("活体验证不通过");
}
return result;
} /***
* 判断身份证认证是否成功
* @param line
* @return
*/
public boolean ocrResultInfos(String line) {
boolean flag = false;
JSONObject json = JSONObject.parseObject(line);
String code = json.getString("code");
String passed = json.getString("passed");
Object liveness_score = json.get("liveness_score");
Double verification_score = json.getDouble("verification_score");
Object image_id = json.get("image_id");
Object image_timestamp = json.get("image_timestamp");
Object base64_image = json.get("base64_image");
Object request_id = json.get("request_id");
if ("true".equals(passed) && "1000".equals(code)) {
if (rangeInDefined(verification_score)) {
flag = true;
return flag;
}
}
return flag;
} /***
* 判断身份证认证是否成功
* @param line
* @return
*/
public boolean idcardResultInfos(String line) {
boolean flag = false;
JSONObject json = JSONObject.parseObject(line);
String code = json.getString("code");
String validity = json.getString("validity");
String side = json.getString("side");
JSONObject validityJson = JSONObject.parseObject(validity);
if ("1000".equals(code) && "front".equals(side)) {
String name = validityJson.getString("name");
String gender = validityJson.getString("gender");
String address = validityJson.getString("address");
String number = validityJson.getString("number");
String birthday = validityJson.getString("birthday");
if ("true".equals(name) && "true".equals(gender) && "true".equals(address) && "true".equals(number) && "true".equals(birthday)) {
flag = true;
}
} else if ("1000".equals(code) && "back".equals(side)) {
String authority = validityJson.getString("authority");
String timelimit = validityJson.getString("timelimit");
if ("true".equals(authority) && "true".equals(timelimit)) {
flag = true;
}
}
return flag;
} /***
* 判断人脸比对得分阈值在0.5到1的区间
* @param current
* @return
*/
public boolean rangeInDefined(double current) {
double min = 0.5;
double max = 1.0;
return Math.max(min, current) == Math.min(current, max);
} public Map fileReName(MultipartFile file) {
Map<String, Object> map = new HashMap<String, Object>();
// 文件名
String filename = file.getOriginalFilename();
// 获取文件名
String prefixname = filename.substring(0, filename.lastIndexOf("."));
// 获取文件后缀名
String suffixname = filename.substring(filename.lastIndexOf(".") + 1); String proFileName = String.valueOf(System.currentTimeMillis());
proFileName = prefixname + proFileName;
map.put("filename", filename);
map.put("prefixname", prefixname);
map.put("suffixname", suffixname);
map.put("proFileName", proFileName);
return map;
} /**
* 上传文件
*/
public String upLoad(File file) {
String endpoint = this.endpoint;
String accessKeyId = this.accessId;
String accessKeySecret = this.accessKey;
String bucketName = this.bucket;
String fileHost = this.host;
String dir = this.dir;
// 判断文件
if (file == null) {
return null;
}
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
// 判断容器是否存在,不存在就创建
if (!client.doesBucketExist(bucketName)) {
client.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
client.createBucket(createBucketRequest);
}
InputStream in = new FileInputStream(file);
final String Random = RandomNumUtil.RandomChar();
// 设置文件路径和名称
String fileUrl = fileHost + "/" + (dir + Random + file.getName());
// 上传文件
PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, dir + Random + file.getName(), in));
// 设置权限(公开读)
client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (result != null) {
// logger.info("------OSS文件上传成功------" + fileUrl);
return fileUrl;
}
} catch (OSSException oe) {
oe.printStackTrace();
logger.error(oe.getMessage());
} catch (ClientException ce) {
ce.printStackTrace();
logger.error(ce.getErrorMessage());
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (client != null) {
client.shutdown();
}
}
return null;
} // ffmpeg -i C:\Users\10375\Desktop\learner-demo.m4v -b:v 400k -s 960x540 newfiles/learner-demo.mp4
/**
* 压缩视频
* 功能描述:
* @Author xiyou
* @Description
* @Date 20:29 2019/4/15
* @Param
* @return
**/
public void convetors(MultipartFile file, String proFileName, String suffixName)
throws Exception {
String fileName = getFileName(file);
File source = new File(fileName);
File target = new File(proFileName + "." + suffixName);
List<String> command = new ArrayList<String>();
command.add(ffmpegEXE);
command.add("-i");
command.add(String.valueOf(source));
command.add("-b:v");
command.add("400k");
command.add("-s");
command.add("544x960");
command.add(String.valueOf(target));
System.out.println("命令:" + command);
ProcessBuilder builder = new ProcessBuilder(command);
Process process = null;
try {
process = builder.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 使用这种方式会在瞬间大量消耗CPU和内存等系统资源,所以这里我们需要对流进行处理
InputStream errorStream = process.getErrorStream();
InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
BufferedReader br = new BufferedReader(inputStreamReader); String line = "";
while ((line = br.readLine()) != null) {
}
if (br != null) {
br.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (errorStream != null) {
errorStream.close();
} } }
调用ffmpeg视频压缩工具类的更多相关文章
- Java调用FFmpeg进行视频处理及Builder设计模式的应用
1.FFmpeg是什么 FFmpeg(https://www.ffmpeg.org)是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.它用来干吗呢?视频采集.视频格式转化.视频 ...
- javaCV入门指南:调用FFmpeg原生API和JavaCV是如何封装了FFmpeg的音视频操作?
通过"javaCV入门指南:序章 "大家知道了处理音视频流媒体的前置基本知识,基本知识包含了像素格式.编解码格式.封装格式.网络协议以及一些音视频专业名词,专业名词不会赘述,自行搜 ...
- NET 2.0(C#)调用ffmpeg处理视频的方法
另外:ffmpeg的net封装库 http://www.intuitive.sk/fflib/ NET 2.0 调用FFMPEG,并异步读取输出信息的代码...public void ConvertV ...
- ASP.NET下调用ffmpeg与mencoder实现视频转换截屏
最近要做一个视频播放的系统,用到了ffmpeg和mencoder两个工具,查了一些资料,发现这方面的资料还挺多的,但是就是乱了一点,我自己从头整理了一下,和大家分享一下: 1.ffmpeg实现视频(a ...
- .Net调用ffmpeg对视频截图
2019/10/27, .Net c#代码片段 摘要:借助ffmpeg对视频/图片截图.生成缩略图,使用命令行调用ffmpeg工具,支持Linux和Windows 网上很多版本都是需要等待4s的做法, ...
- C#进程调用FFmpeg操作音视频
项目背景 因为公司需要对音视频做一些操作,比如说对系统用户的发音和背景视频进行合成,以及对多个音视频之间进行合成,还有就是在指定的源背景音频中按照对应的规则在视频的多少秒钟内插入一段客户发音等一些复杂 ...
- ffdshow 源代码分析 7: libavcodec视频解码器类(TvideoCodecLibavcodec)
===================================================== ffdshow源代码分析系列文章列表: ffdshow 源代码分析 1: 整体结构 ffds ...
- moviepy音视频剪辑:视频基类VideoClip子类VideoFileClip、CompositeVideoClip、ImageSequenceClip介绍
☞ ░ 前往老猿Python博文目录 ░ 一.引言 在<moviepy音视频剪辑:moviepy中的剪辑相关类及关系>介绍了VideoClip主要有六个直接子类(VideoFileClip ...
- bash shell,调用ffmpeg定期截图
#!/bin/bash #获取当前目录中所有m3u8文件,并 var=$(ls |grep '.m3u8'|cut -d '.' -f1) #死循环 = ] do #循环每个文件 for stream ...
随机推荐
- HBase 学习之路(七)——HBase过滤器详解
一.HBase过滤器简介 Hbase提供了种类丰富的过滤器(filter)来提高数据处理的效率,用户可以通过内置或自定义的过滤器来对数据进行过滤,所有的过滤器都在服务端生效,即谓词下推(predica ...
- swoole异步任务数据报表生成
<?php include 'vendor/autoload.php'; class server { private $serv; private $db; /** * [__construc ...
- 字节跳动Java研发面试99题(含答案):JVM+Spring+MySQL+线程池+锁
JVM的内存结构 根据 JVM 规范,JVM 内存共分为虚拟机栈.堆.方法区.程序计数器.本地方法栈五个部分. 1. Java虚拟机栈:线程私有:每个方法在执行的时候会创建一个栈帧,存储了局部变量表, ...
- CentOS下查看机器配置
1.查看系统位数.内核版本 [root@localhost ~]# uname -a Linux localhost.localdomain 3.10.0-693.11.6.el7.x86_64 #1 ...
- python数据分析与挖掘实战
<python数据分析与挖掘实战>PDF&源代码&张良均 下载:链接:https://pan.baidu.com/s/1TYb3WZOU0R5VbSbH6JfQXw提取码: ...
- python基本数据类型之数字类型和其相关运算
数字(number) Python3 支持 int.float.bool.complex(复数). 在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long. ...
- 字符串匹配Boyer-Moore算法:文本编辑器中的查找功能是如何实现的?---这应该讲的最容易懂的文章了!
关于字符串匹配算法有很多,之前我有讲过一篇 KMP 匹配算法:图解字符串匹配 KMP 算法,不懂 kmp 的建议看下,写的还不错,这个算法虽然很牛逼,但在实际中用的并不是特别多.至于选择哪一种字符串匹 ...
- Java线程池原理浅析
什么是线程池? 为了避免频繁重复的创建和销毁线程,我们可以让这些线程进行复用,在线程池中,总会有活跃的线程在占用,但是线程池中也会存在没有占用的线程,这些线程处于空闲状态,当有任务的时候会从池子里面拿 ...
- SpringBoot项目构建成jar运行后,如何正确读取resource下的文件
SpringBoot项目构建成jar运行后,如何正确读取resource下的文件 不管你使用的是SpringBoot 1.x还是SpringBoot2.x,在开Dev环境中使用eclipse.IEAD ...
- Python面向对象知多少?
问题场景 小王是某游戏公司的新入职的职员,有一天,组长交给了他一个任务,为一个即将准开发的一款游戏设计一些人物角色,其中包括多种职业,如牧师.战士和法师等等.每种职业都有一些自身独有的属性和技能,但是 ...