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. 点菜网---Java开源生鲜电商平台-技术选型(源码可下载)

    点菜网---Java开源生鲜电商平台-技术选型(源码可下载) 1.内容简介 点菜网目前选用的是最流行的微服务架构模式,采用前后端分离的开发模式,具备高可用,高负载,支持千万级别的数据量的请求. 2. ...

  2. Scala 学习之路(七)—— 常用集合类型之 Map & Tuple

    一.映射(Map) 1.1 构造Map // 初始化一个空map val scores01 = new HashMap[String, Int] // 从指定的值初始化Map(方式一) val sco ...

  3. Java---使用EWS 写个ExchangeMailUtil

    依赖包: commons-httpclient-3.1.jar commons-codec-1.10.jar commons-logging-1.2.jar jcifs-1.3.17.jar 代码示例 ...

  4. 【过时】update progress has encountered a problem解决办法

    笔者第二次整理博客,已经抛弃MyEclipse了,我将公司项目转换成了idea的目录结构后大家都改换Idea进行开发,虽然我个人比较喜欢eclipse的简洁干净,但是Idea的确有很多方便开发的新功能 ...

  5. css之vw布局

    vw,vh是视口单位,是相对视口单位,与百分百布局不一样的是,百分百是相对于父及元素,而vw布局是相对与窗口. 而rem布局是要与js一起配合 // 以iphone6设计稿 @function px2 ...

  6. package.json 详解

    使用package.json  属性说明 name - 包名. version - 包的版本号. description - 包的描述. homepage - 包的官网 url . author - ...

  7. 有用的java学习网站

    1.在线编译运行Java代码的网站 https://www.compilejava.net/ 2. 综合学习网站: http://www.tutorialspoint.com/,可以在线执行多种编程语 ...

  8. pod update更新error: RPC failed; curl 18 transfer closed with outstanding read data remaining

    1. pod update 的时候出现下边的错误 error: RPC failed; curl 18 transfer closed with outstanding read data remai ...

  9. Spring WebFlux之HttpHandler的探索

    这是本人正在写的<Java 编程方法论:响应式Reactor3.Reactor-Netty和Spring WebFlux>一书的文章节选,它是<Java编程方法论:响应式RxJava ...

  10. 剑指offer第二版-2.实现单例模式

    面试题2:实现单例模式 题目要求: 设计一个类,只能生成该类的一个实例. /** * 单例模式 * 定义:指实现了特殊模式的类,该类仅能被实例化一次,产生唯一的一个对象 * 应用举例:windows的 ...