调用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 ...
随机推荐
- Node.js实现PC端类微信聊天软件(二)
Github StackChat 用到的React-Router React-Router是React路由的解决方案之一,也可以使用别的库 安装 npm install react-router -- ...
- 利用Settings.bundle切换网络环境
目的:一次性打包,测试可以去iPhone设置,找到APP,点击后然后可以自主切换网络环境(测试.预生产.正式).关闭APP重新打开生效. 撸起袖子加油干…… 1.生成并设置Setting.bundle ...
- C#常用设计模式--单例模式
为什么要使用单例模式 在我们的整个游戏生命周期当中,有很多对象从始至终有且只有一个.这个唯一的实例只需要生成一次,并且直到游戏结束才需要销毁. 单例模式一般应用于管理器类,或者是一些需要持久化存在的 ...
- Codeforces Round #563 (Div. 2)C
C. Ehab and a Special Coloring Problem 题目链接:http://codeforces.com/contest/1174/problem/C 题目 You're g ...
- Django迁移数据库报错
Django迁移数据库报错 table "xxx" already exists错误 django在migrate时报错django migrate error: table 'x ...
- Jenkins+GitLab+Docker+SpringCloud+Kubernetes实现可持续自动化微服务
现有混合云平台的场景下,即有线下和线上的环境,又有测试与正式的场景,而且结合了Docker,导致打包内容有所区分,且服务的发布流程复杂起来,手工打包需要在编译阶段就要根据环境到处更改配置,因此纯手工发 ...
- vue 跨域请求,后端cookie session取不到
虽然后端设置了可以跨域请求,但是后台设置到cookie中的session取不到!这时候mac电脑自己设置nginx代理! mac电脑系统重装了,记录一下安装nginx的过程: 1.打开终端(cmd) ...
- Linux命令及安装
1.三大操作系统 1.Unix Solaris(SUN) IOS(Aplle移动端) Mas OS(Aplle平板,电脑端) 2.Windows XP win7 win8 win10 3.Linux ...
- python数据库查询转dataframe
1. 场景描述 python环境下需要从greenplum/postgresql中,获取算法执行的数据,但是从数据库中查询出来是数组格式的,算法无法使用,需要转换为dataframe格式. 2. 解决 ...
- Python选修第00次作业:缘分
先说一说我与Python的缘分吧.初识Python,是在高三上学期.从那位同学那里经过时,看到了他桌子上的一本书——<和小卡特一起学Python>,封面就很吸引人,便买来一本,累了不想做题 ...