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视频压缩工具类的更多相关文章

  1. Java调用FFmpeg进行视频处理及Builder设计模式的应用

    1.FFmpeg是什么 FFmpeg(https://www.ffmpeg.org)是一套可以用来记录.转换数字音频.视频,并能将其转化为流的开源计算机程序.它用来干吗呢?视频采集.视频格式转化.视频 ...

  2. javaCV入门指南:调用FFmpeg原生API和JavaCV是如何封装了FFmpeg的音视频操作?

    通过"javaCV入门指南:序章 "大家知道了处理音视频流媒体的前置基本知识,基本知识包含了像素格式.编解码格式.封装格式.网络协议以及一些音视频专业名词,专业名词不会赘述,自行搜 ...

  3. NET 2.0(C#)调用ffmpeg处理视频的方法

    另外:ffmpeg的net封装库 http://www.intuitive.sk/fflib/ NET 2.0 调用FFMPEG,并异步读取输出信息的代码...public void ConvertV ...

  4. ASP.NET下调用ffmpeg与mencoder实现视频转换截屏

    最近要做一个视频播放的系统,用到了ffmpeg和mencoder两个工具,查了一些资料,发现这方面的资料还挺多的,但是就是乱了一点,我自己从头整理了一下,和大家分享一下: 1.ffmpeg实现视频(a ...

  5. .Net调用ffmpeg对视频截图

    2019/10/27, .Net c#代码片段 摘要:借助ffmpeg对视频/图片截图.生成缩略图,使用命令行调用ffmpeg工具,支持Linux和Windows 网上很多版本都是需要等待4s的做法, ...

  6. C#进程调用FFmpeg操作音视频

    项目背景 因为公司需要对音视频做一些操作,比如说对系统用户的发音和背景视频进行合成,以及对多个音视频之间进行合成,还有就是在指定的源背景音频中按照对应的规则在视频的多少秒钟内插入一段客户发音等一些复杂 ...

  7. ffdshow 源代码分析 7: libavcodec视频解码器类(TvideoCodecLibavcodec)

    ===================================================== ffdshow源代码分析系列文章列表: ffdshow 源代码分析 1: 整体结构 ffds ...

  8. moviepy音视频剪辑:视频基类VideoClip子类VideoFileClip、CompositeVideoClip、ImageSequenceClip介绍

    ☞ ░ 前往老猿Python博文目录 ░ 一.引言 在<moviepy音视频剪辑:moviepy中的剪辑相关类及关系>介绍了VideoClip主要有六个直接子类(VideoFileClip ...

  9. bash shell,调用ffmpeg定期截图

    #!/bin/bash #获取当前目录中所有m3u8文件,并 var=$(ls |grep '.m3u8'|cut -d '.' -f1) #死循环 = ] do #循环每个文件 for stream ...

随机推荐

  1. 【】input中 type=number 去掉箭头

    css中设置: input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: non ...

  2. 【maven 】jar包冲突-记一次冲突解决

    方法一:根据mvn提示一个一个排除 1.请到pom.xml文件所在的目录(包含父子目录)下分别执行下面的命令排查是什么原因导致fastjson版本不正确: mvn dependency:tree -D ...

  3. 【JDK8】HashMap集合 源码阅读

    JDK8的HashMap数据结构上复杂了很多,因此读取效率得以大大提升,关于源码中红黑树的增删改查,博主没有细读,会在下一篇博文中使用Java实现红黑树的增删改查. 下面是类的结构图: 代码(摘抄自J ...

  4. logrotate切割nginx日志

    1 配置 使用系统自带的logrorate来切个nginx日志,位于/usr/sbin/logrotate 假设服务器上有两个网站的nginx配置分别如下: 去除其它配置信息,只保留了日志相关 A网站 ...

  5. springboot+redis+Interceptor+自定义annotation实现接口自动幂等

    前言: 在实际的开发项目中,一个对外暴露的接口往往会面临很多次请求,我们来解释一下幂等的概念:任意多次执行所产生的影响均与一次执行的影响相同.按照这个含义,最终的含义就是 对数据库的影响只能是一次性的 ...

  6. 项目中遇到的Redis缓存问题

    1.Redis服务器 can not get resource from pool. 1000个线程并发还能跑,5000个线程的时候出现这种问题,查后台debug日志,发现redis 线程池不够.刚开 ...

  7. kubernetes实战之consul篇及consul在windows下搭建consul简单测试环境

    consul是一款服务发现中间件,1.12版本后增加servicemesh功能.consul是分布式的,可扩展的,高可用的根据官方文档介绍,目前已知最大的consul集群有5000个节点,consul ...

  8. linux 多主机间快速跳转脚本

    #!/usr/bin/env python #coding=utf8 ''' 用于多机器间相互跳转,如有新机器加入,需要更新ip_list文件 ''' from prettytable import ...

  9. 设计模式-访问者模式(Visitor)

    访问者模式是行为模式的一种.访问者模式的基本想法是,软件系统中拥有一个由许多对象构成的.比较稳定的对象结构,这些对象的类都拥有一个accept方法用来接受访问者的访问.访问者是一个接口,它拥有一个vi ...

  10. CentOS 操作防火墙

    1:查看防火状态 systemctl status firewalld 2:暂时关闭防火墙 systemctl stop firewalld 3:永久关闭防火墙 systemctl disable f ...