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();
} } }

最新文章

  1. android接收短信——framework处理流程(android 5.1)
  2. JQUERY操作css与css()方法、获取设置尺寸;
  3. scrollTop,offset().top
  4. Android入门第十六篇之Style与Theme [转]
  5. 转: requirejs压缩打包r.js使用示例 2 (~~很详细的教程)
  6. golang做的邮件服务器
  7. NewtonJson中转义的斜杠\和多余的引号处理
  8. Python LeetCode
  9. linux ftp及C/S服务架构
  10. 使用Netty实现HTTP服务器
  11. Node.js实战项目学习系列(1) 初识Node.js
  12. mongoDB(2)--mongoDB的常用命令
  13. JVM调优常用参数和注意点备忘录
  14. Bootstrap 框架
  15. Oracle 使用PDB 的情况下进行备份恢复的使用.
  16. Android自动化测试探索
  17. markdown-to-html.min.js
  18. Delphi动态调用C++写的DLL
  19. C# 字符串的操作
  20. Windows系统日常运维

热门文章

  1. docker容器中使用pip有警告
  2. Oracle基础学习笔记
  3. 破坏之王-DDoS攻击与防范深度剖析
  4. Python爬虫的起点
  5. HDU 5775:Bubble Sort(树状数组)
  6. redis RDB 和AOF
  7. shiro自定义异常无法被捕获总是抛出AuthenticationException解决方案
  8. CentOS 6.5 下安装及使用中文输入法
  9. python对Excel的读取
  10. 基于 Jmeter 的 web 端接口自动化测试平台(转载)