first commit
This commit is contained in:
159
dcsoft-modules/dcsoft-file/src/main/java/com/Main.java
Normal file
159
dcsoft-modules/dcsoft-file/src/main/java/com/Main.java
Normal file
@@ -0,0 +1,159 @@
|
||||
package com;
|
||||
|
||||
import com.uniubi.Register.FaceBox;
|
||||
import com.uniubi.Register.UfaceRegister;
|
||||
import com.uniubi.Register.UfaceRegisterJNI;
|
||||
|
||||
import javax.imageio.stream.FileImageOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Objects;
|
||||
|
||||
class MyThread extends Thread {
|
||||
private final String name;
|
||||
private final File[] files;
|
||||
|
||||
public MyThread(String name, File[] files) {
|
||||
this.name = name;
|
||||
this.files = files;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
System.out.println("SDK version : " + UfaceRegisterJNI.GetSDKVersion());
|
||||
UfaceRegister.SetLogMode(2);
|
||||
// UfaceRegister.SetModelPath("");
|
||||
int res = UfaceRegister.Auth("dongbang", "NvJZ9pHhVbtX", "verify.lic");
|
||||
System.out.println("Auth status : " + res);
|
||||
UfaceRegister u = new UfaceRegister();
|
||||
int need_handle_num = files.length;
|
||||
for (int i = 0; i < need_handle_num; i++) {
|
||||
try {
|
||||
byte[] image1 = Files.readAllBytes(new File(files[i].toString()).toPath());
|
||||
FaceBox box1 = new FaceBox();
|
||||
// res = u.JudgeImage(image1, box1);
|
||||
float score = u.DynamicQuality(image1, box1);
|
||||
System.out.println(name + ",i = " + i + ",all" + need_handle_num + ",fileName = " + files[i] + ",code " + box1.code + " score " + score);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
u.release();
|
||||
}
|
||||
}
|
||||
|
||||
public class Main {
|
||||
public static void test_GetSimpleImage() {
|
||||
System.out.println("SDK version : " + UfaceRegisterJNI.GetSDKVersion());
|
||||
UfaceRegister.SetLogMode(2);
|
||||
//UfaceRegister.SetModelPath("");
|
||||
int res = UfaceRegister.Auth("decheng", "kbSfmCwalEFU", "verify.lic");
|
||||
System.out.println("Auth status : " + res);
|
||||
UfaceRegister u = new UfaceRegister();
|
||||
String path = "";
|
||||
File file = new File(path);
|
||||
File[] tempList = file.listFiles();
|
||||
|
||||
try {
|
||||
for (int i = 0; i < Objects.requireNonNull(tempList).length; i++) {
|
||||
System.out.println(tempList[i] + " " + i);
|
||||
byte[] image = Files.readAllBytes(new File(tempList[i].toString()).toPath());
|
||||
FaceBox box = new FaceBox();
|
||||
res = u.JudgeImage(image, box);
|
||||
if (res == 0) {
|
||||
String feature_src = u.GetFeature(image, 110, box);
|
||||
System.out.println("before box xmin:" + box.xmin + ",ymin:" + box.ymin + ",xmax:" + box.xmax + ",ymax:" + box.ymax);
|
||||
byte[] small_image = u.GetSimpleImage(image, box, 1, 300);
|
||||
System.out.println("after box xmin:" + box.xmin + ",ymin:" + box.ymin + ",xmax:" + box.xmax + ",ymax:" + box.ymax);
|
||||
if (small_image != null) {
|
||||
FileImageOutputStream os = new FileImageOutputStream(new File("test.jpg"));
|
||||
System.out.println("small_image.length : " + small_image.length);
|
||||
os.write(small_image, 0, small_image.length);
|
||||
os.flush();
|
||||
os.close();
|
||||
}
|
||||
String feature = u.GetFeature(small_image, 110, box);
|
||||
float score = u.CompareFeat(feature_src, feature);
|
||||
System.out.println("score : " + score);
|
||||
// System.out.println("feature : " + feature);
|
||||
} else {
|
||||
System.out.println("res == " + res);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
//test_thread
|
||||
// test_thread();
|
||||
//test_GetSimpleImage
|
||||
// test_GetSimpleImage();
|
||||
//test_compare_two_pic
|
||||
test_compare_two_pic();
|
||||
}
|
||||
|
||||
public static void test_compare_two_pic() {
|
||||
System.out.println("SDK version : " + UfaceRegisterJNI.GetSDKVersion());
|
||||
UfaceRegister.SetLogMode(2);
|
||||
UfaceRegister.SetModelPath("/usr/uface_sdk/models");
|
||||
int res = UfaceRegister.Auth("decheng","kbSfmCwalEFU", "verify.lic");
|
||||
System.out.println("Auth status : " + res);
|
||||
UfaceRegister u = new UfaceRegister();
|
||||
|
||||
try {
|
||||
byte[] image1 = Files.readAllBytes(new File("/usr/face_img/A003.jpg").toPath());
|
||||
FaceBox box1 = new FaceBox();
|
||||
int res1 = u.JudgeImage(image1, box1);
|
||||
String feature1 = "";
|
||||
if (res1 == 0) {
|
||||
feature1 = u.GetFeature(image1, 110, box1);
|
||||
} else {
|
||||
System.out.println("res1 == " + res1);
|
||||
}
|
||||
|
||||
byte[] image2 = Files.readAllBytes(new File("/usr/face_img/A004.jpg").toPath());
|
||||
FaceBox box2 = new FaceBox();
|
||||
int res2 = u.JudgeImage(image2, box2);
|
||||
String feature2 = "";
|
||||
if (res2 == 0) {
|
||||
feature2 = u.GetFeature(image2, 110, box2);
|
||||
} else {
|
||||
System.out.println("res2 == " + res2);
|
||||
}
|
||||
|
||||
float score = u.CompareFeat(feature1, feature2);
|
||||
System.out.println("score : " + score);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void test_thread() {
|
||||
int thread_num = 1;
|
||||
|
||||
String path = "";
|
||||
File file = new File(path);
|
||||
File[] tempList = file.listFiles();
|
||||
assert tempList != null;
|
||||
int per_thread_handle_nums = tempList.length / thread_num;
|
||||
System.out.println(" per_thread_handle_nums: " + per_thread_handle_nums);
|
||||
for (int i = 0; i < thread_num; i++) {
|
||||
if (i != thread_num - 1) {
|
||||
File[] test = new File[per_thread_handle_nums];
|
||||
System.arraycopy(tempList, i * per_thread_handle_nums, test, 0, per_thread_handle_nums);
|
||||
MyThread mt = new MyThread("thread" + i, test);
|
||||
mt.start();
|
||||
} else {
|
||||
File[] test = new File[per_thread_handle_nums + tempList.length % thread_num];
|
||||
System.arraycopy(tempList, i * per_thread_handle_nums, test, 0, per_thread_handle_nums + tempList.length % thread_num);
|
||||
MyThread mt = new MyThread("thread" + i, test);
|
||||
mt.start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.dcsoft.file;
|
||||
|
||||
import com.dcsoft.file.config.FileListener;
|
||||
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import com.dcsoft.common.swagger.annotation.EnableCustomSwagger2;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 文件服务
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
@EnableCustomSwagger2
|
||||
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
|
||||
public class DCSFileApplication
|
||||
{
|
||||
/* public static String rootDir;
|
||||
|
||||
@Value("${backImg.rootDir}")
|
||||
public void setRootDir(String rootDir) {
|
||||
this.rootDir = rootDir;
|
||||
}
|
||||
|
||||
public static String copyDir;
|
||||
|
||||
@Value("${backImg.copyDir}")
|
||||
public void setCopyDir(String copyDir) {
|
||||
this.copyDir = copyDir;
|
||||
}*/
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
SpringApplication.run(DCSFileApplication.class, args);
|
||||
System.out.println("(♥◠‿◠)ノ゙ 文件服务模块启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||
" ___ ___ ___ \n" +
|
||||
" | \\ / __| / __| \n" +
|
||||
" | |) | | (__ \\__ \\ \n" +
|
||||
" |___/ \\___| |___/ ");
|
||||
|
||||
/* // 轮询间隔 5 秒
|
||||
long interval = TimeUnit.SECONDS.toMillis(5);
|
||||
// 不使用过滤器
|
||||
FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir));
|
||||
observer.addListener(new FileListener(rootDir,copyDir));
|
||||
// 创建文件变化监听器
|
||||
FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
|
||||
// 开始监控
|
||||
try {
|
||||
monitor.start();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}*/
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.dcsoft.file.config;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
|
||||
import org.apache.commons.io.monitor.FileAlterationMonitor;
|
||||
import org.apache.commons.io.monitor.FileAlterationObserver;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
public class FileListener extends FileAlterationListenerAdaptor {
|
||||
|
||||
public String rootDir;
|
||||
public String copyDir;
|
||||
|
||||
public FileListener(String root, String copy) {
|
||||
this.rootDir=root;
|
||||
this.copyDir=copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件创建执行
|
||||
*/
|
||||
public void onFileCreate(File file) {
|
||||
log.info("[新建]:" + file.getPath());
|
||||
//文件同步到另一个文件夹中
|
||||
String path=file.getPath().replace(rootDir,copyDir);
|
||||
File dest=new File(path);
|
||||
if (!(dest.exists() && dest.isDirectory())) {
|
||||
new File(path.substring(0, path.lastIndexOf(File.separator))).mkdirs();
|
||||
}
|
||||
try {
|
||||
Files.copy(file.toPath(), dest.toPath());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 文件修改
|
||||
*/
|
||||
public void onFileChange(File file) {
|
||||
log.info("[修改]:" + file.getAbsolutePath());
|
||||
}
|
||||
/**
|
||||
* 文件删除
|
||||
*/
|
||||
public void onFileDelete(File file) {
|
||||
log.info("[删除]:" + file.getAbsolutePath());
|
||||
}
|
||||
/**
|
||||
* 目录创建
|
||||
*/
|
||||
public void onDirectoryCreate(File directory) {
|
||||
log.info("[新建]:" + directory.getAbsolutePath());
|
||||
}
|
||||
/**
|
||||
* 目录修改
|
||||
*/
|
||||
public void onDirectoryChange(File directory) {
|
||||
log.info("[修改]:" + directory.getAbsolutePath());
|
||||
}
|
||||
/**
|
||||
* 目录删除
|
||||
*/
|
||||
public void onDirectoryDelete(File directory) {
|
||||
log.info("[删除]:" + directory.getAbsolutePath());
|
||||
}
|
||||
public void onStart(FileAlterationObserver observer) {
|
||||
super.onStart(observer);
|
||||
}
|
||||
public void onStop(FileAlterationObserver observer) {
|
||||
super.onStop(observer);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.dcsoft.file.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import io.minio.MinioClient;
|
||||
|
||||
/**
|
||||
* Minio 配置信息
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "minio")
|
||||
public class MinioConfig
|
||||
{
|
||||
/**
|
||||
* 服务地址
|
||||
*/
|
||||
private String url;
|
||||
|
||||
/**
|
||||
* 用户名
|
||||
*/
|
||||
private String accessKey;
|
||||
|
||||
/**
|
||||
* 密码
|
||||
*/
|
||||
private String secretKey;
|
||||
|
||||
/**
|
||||
* 存储桶名称
|
||||
*/
|
||||
private String bucketName;
|
||||
|
||||
public String getUrl()
|
||||
{
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url)
|
||||
{
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getAccessKey()
|
||||
{
|
||||
return accessKey;
|
||||
}
|
||||
|
||||
public void setAccessKey(String accessKey)
|
||||
{
|
||||
this.accessKey = accessKey;
|
||||
}
|
||||
|
||||
public String getSecretKey()
|
||||
{
|
||||
return secretKey;
|
||||
}
|
||||
|
||||
public void setSecretKey(String secretKey)
|
||||
{
|
||||
this.secretKey = secretKey;
|
||||
}
|
||||
|
||||
public String getBucketName()
|
||||
{
|
||||
return bucketName;
|
||||
}
|
||||
|
||||
public void setBucketName(String bucketName)
|
||||
{
|
||||
this.bucketName = bucketName;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MinioClient getMinioClient()
|
||||
{
|
||||
return MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.dcsoft.file.config;
|
||||
|
||||
import java.io.File;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* 通用映射配置
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
@Configuration
|
||||
public class ResourcesConfig implements WebMvcConfigurer
|
||||
{
|
||||
/**
|
||||
* 上传文件存储在本地的根路径
|
||||
*/
|
||||
@Value("${file.path}")
|
||||
private String localFilePath;
|
||||
|
||||
/**
|
||||
* 资源映射路径 前缀
|
||||
*/
|
||||
@Value("${file.prefix}")
|
||||
public String localFilePrefix;
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry)
|
||||
{
|
||||
/** 本地文件上传路径 */
|
||||
registry.addResourceHandler(localFilePrefix + "/**")
|
||||
.addResourceLocations("file:" + localFilePath + File.separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 开启跨域
|
||||
*/
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
// 设置允许跨域的路由
|
||||
registry.addMapping(localFilePrefix + "/**")
|
||||
// 设置允许跨域请求的域名
|
||||
.allowedOrigins("*")
|
||||
// 设置允许的方法
|
||||
.allowedMethods("GET");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.dcsoft.file.controller;
|
||||
|
||||
import io.minio.BucketExistsArgs;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectArgs;
|
||||
import io.minio.RemoveObjectArgs;
|
||||
import lombok.Data;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
public class MinIO {
|
||||
|
||||
private String address; //IP地址
|
||||
private String userName; //用户名
|
||||
private String password; //密码
|
||||
private MinioClient minioClient; //操作对象
|
||||
MinIO(String address, String userName, String password) {
|
||||
this.address = address;
|
||||
this.userName = userName;
|
||||
this.password = password;
|
||||
}
|
||||
//获取操作对象:
|
||||
public MinioClient getMinioClient() {
|
||||
if (this.minioClient == null) {
|
||||
this.minioClient = MinioClient.builder()
|
||||
.endpoint(this.getAddress())
|
||||
.credentials(this.getUserName(), this.getPassword())
|
||||
.build();
|
||||
}
|
||||
return this.minioClient;
|
||||
}
|
||||
//上传文件:
|
||||
public String upload(MultipartFile multipartFile, String bucketName) throws Exception {
|
||||
//一、设置文件存放的路径信息
|
||||
String fileName = multipartFile.getName(); //获取文件名称:
|
||||
String timeRandom = String.valueOf(System.currentTimeMillis()); //获取当前时间戳:
|
||||
fileName = timeRandom + "_" + fileName; //拼接文件名:
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //格式化当前日期:
|
||||
String objectName = sdf.format(new Date()) + "/" + fileName; //最后存储的路径: 格式为:时间/文件
|
||||
//二、上传文件
|
||||
this.getMinioClient().putObject(PutObjectArgs.builder().
|
||||
bucket(bucketName) //桶名称
|
||||
.object(objectName) //路径
|
||||
//以下为默认配置:
|
||||
.stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
|
||||
.contentType(multipartFile.getContentType())
|
||||
.build());
|
||||
//三、访问路径:
|
||||
return this.address + "/" + bucketName + "/" + objectName;
|
||||
}
|
||||
//删除文件:
|
||||
public void delete(String bucketName,String fileName) {
|
||||
/**
|
||||
* String bucketName = "test2";
|
||||
* String fileName = "/2023-04-07/16808560218465670_img.png";
|
||||
* address+bucketName+fileName 就是访问路径,删除需要后两个参数。
|
||||
*/
|
||||
try {
|
||||
this.getMinioClient().removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
|
||||
} catch (Exception e) {
|
||||
System.out.println("删除失败");
|
||||
}
|
||||
System.out.println("删除成功");
|
||||
}
|
||||
//查询某个桶是否存在:
|
||||
public Boolean isExit(String bucketName) throws Exception {
|
||||
boolean found =
|
||||
this.getMinioClient().bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
|
||||
if (found) {
|
||||
System.out.println("存储桶存在!");
|
||||
return true;
|
||||
} else {
|
||||
System.out.println("存储桶不存在!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
package com.dcsoft.file.controller;
|
||||
|
||||
import com.alibaba.csp.sentinel.slots.block.BlockException;
|
||||
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
|
||||
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.dcsoft.common.core.exception.ServiceException;
|
||||
import com.dcsoft.file.service.IAlgoService;
|
||||
import com.dcsoft.file.service.IFaceService;
|
||||
import com.dcsoft.file.utils.*;
|
||||
import com.dcsoft.system.api.RemoteStudentService;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.RemoveObjectArgs;
|
||||
import net.coobird.thumbnailator.Thumbnails;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.dcsoft.common.core.domain.R;
|
||||
import com.dcsoft.common.core.utils.file.FileUtils;
|
||||
import com.dcsoft.file.service.ISysFileService;
|
||||
import com.dcsoft.system.api.domain.SysFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.dcsoft.file.utils.MinioUtil.getBase64String;
|
||||
|
||||
/**
|
||||
* 文件请求处理
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
@RestController
|
||||
public class SysFileController
|
||||
{
|
||||
private static final Logger log = LoggerFactory.getLogger(SysFileController.class);
|
||||
|
||||
/** 获取yml配置类里的桶名称*/
|
||||
@Value("${minio.bucket-name}")
|
||||
private String bucketName;
|
||||
|
||||
@Autowired
|
||||
private ISysFileService sysFileService;
|
||||
|
||||
@Value("${minio.bucket-name1}")
|
||||
private String bucketName1;
|
||||
|
||||
@Autowired
|
||||
private IAlgoService algoService;
|
||||
|
||||
@Autowired
|
||||
private IFaceService faceService;
|
||||
|
||||
@Value("${minio.accessKey}")
|
||||
private String accessKey;
|
||||
|
||||
@Value("${minio.secretKey}")
|
||||
private String secretKey;
|
||||
|
||||
@Value("${minio.url}")
|
||||
private String miniourl;
|
||||
|
||||
@Value("${sdk.upload}")
|
||||
public String upload;
|
||||
|
||||
@Value("${minio.gwurl}")
|
||||
private String miniogwurl;
|
||||
|
||||
@Value("${minio.bucket-name2}")
|
||||
private String bucketName2;
|
||||
|
||||
@Value("${file.domain}")
|
||||
private String fileurl;
|
||||
|
||||
@Value("${file.gwurl}")
|
||||
private String filegwurl;
|
||||
|
||||
/**
|
||||
* 文件上传请求
|
||||
*/
|
||||
@PostMapping("upload")
|
||||
public R<SysFile> upload(MultipartFile file)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 上传并返回访问地址
|
||||
String url = sysFileService.uploadFile(file);
|
||||
SysFile sysFile = new SysFile();
|
||||
sysFile.setName(FileUtils.getName(url));
|
||||
url=url.replace(fileurl,filegwurl);
|
||||
sysFile.setUrl(url);
|
||||
return R.ok(sysFile);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传请求
|
||||
*/
|
||||
@PostMapping("avatar")
|
||||
public R<SysFile> avatar(@RequestParam("avatarfile") MultipartFile file)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 上传并返回访问地址
|
||||
String url = sysFileService.uploadFile(file);
|
||||
SysFile sysFile = new SysFile();
|
||||
sysFile.setName(FileUtils.getName(url));
|
||||
sysFile.setUrl(url);
|
||||
return R.ok(sysFile);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("uploadMinioCar")
|
||||
public R<SysFile> uploadMinioCar(@RequestParam("file") MultipartFile file)
|
||||
{
|
||||
try
|
||||
{
|
||||
String fileNames = FileUploadUtils.uploadMinio(file,this.bucketName2,file.getName());
|
||||
SysFile sysFile = new SysFile();
|
||||
sysFile.setName(FileUtils.getName(fileNames));
|
||||
fileNames=fileNames.replace(miniourl,miniogwurl);
|
||||
sysFile.setUrl(fileNames);
|
||||
return R.ok(sysFile);
|
||||
}catch (Exception e){
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 文件上传请求
|
||||
*/
|
||||
@PostMapping("uploadMinio")
|
||||
public R<SysFile> uploadMinio(MultipartFile file, String fileName)
|
||||
{
|
||||
/* //判断压缩图片
|
||||
if((1024 * 1024 * 0.1) <= file.getSize()){
|
||||
// 小于 1M 的
|
||||
try {
|
||||
String fileNames1 = file.getOriginalFilename();
|
||||
File newFile = new File(fileNames1);
|
||||
if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.4f).toFile(newFile);
|
||||
}
|
||||
// 1 - 2M 的
|
||||
else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.2f).toFile(newFile);
|
||||
}
|
||||
// 2M 以上的
|
||||
else if ((1024 * 1024 * 2) < file.getSize()) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.1f).toFile(newFile);
|
||||
}
|
||||
// 转为 MultipartFile
|
||||
file = PictureUtils.getMultipartFile(newFile);
|
||||
newFile.delete();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}*/
|
||||
try
|
||||
{
|
||||
/*initFlowRules();//
|
||||
// 上传并返回访问地址
|
||||
//上传前进行人脸检测
|
||||
String base64String=MinioUtil.getBase64String(file);
|
||||
int data=faceService.judgeImageBase64(base64String);
|
||||
log.info("人脸检测返回值==========="+data);
|
||||
if(data!=0){
|
||||
log.error("人脸检测不符合要求");
|
||||
return R.fail("人脸检测不符合要求");
|
||||
}
|
||||
//提取特征值
|
||||
String feature=faceService.getFeature(base64String);*/
|
||||
String fileNames = FileUploadUtils.uploadMinio(file,this.bucketName,fileName);
|
||||
SysFile sysFile = new SysFile();
|
||||
sysFile.setName(FileUtils.getName(fileNames));
|
||||
fileNames=fileNames.replace(miniourl,miniogwurl);
|
||||
|
||||
sysFile.setUrl(fileNames);
|
||||
//sysFile.setFeature(feature);
|
||||
return R.ok(sysFile);
|
||||
}catch (Exception e){
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传请求
|
||||
*/
|
||||
@PostMapping("uploadMinios")
|
||||
public R<SysFile> uploadMinios(MultipartFile file,String fileName)
|
||||
{
|
||||
|
||||
//判断压缩图片
|
||||
if((1024 * 1024 * 0.1) <= file.getSize()){
|
||||
// 小于 1M 的
|
||||
try {
|
||||
String fileNames1 = file.getOriginalFilename();
|
||||
File newFile = new File(fileNames1);
|
||||
if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.4f).toFile(newFile);
|
||||
}
|
||||
// 1 - 2M 的
|
||||
else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.2f).toFile(newFile);
|
||||
}
|
||||
// 2M 以上的
|
||||
else if ((1024 * 1024 * 2) < file.getSize()) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.1f).toFile(newFile);
|
||||
}
|
||||
// 获取输入流
|
||||
FileInputStream input = new FileInputStream(newFile);
|
||||
// 转为 MultipartFile
|
||||
file = PictureUtils.getMultipartFile(newFile);
|
||||
newFile.delete();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
// 上传并返回访问地址
|
||||
String fileNames = FileUploadUtils.uploadMinio(file,this.bucketName,fileName);
|
||||
SysFile sysFile = new SysFile();
|
||||
sysFile.setName(FileUtils.getName(fileNames));
|
||||
sysFile.setUrl(fileNames);
|
||||
return R.ok(sysFile);
|
||||
}catch (Exception e){
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件非证件照上传请求
|
||||
*/
|
||||
@PostMapping("uploadMinio1")
|
||||
public R<SysFile> uploadMinio1(MultipartFile file, String fileName) {
|
||||
try {
|
||||
//判断压缩图片
|
||||
if ((1024 * 1024 * 0.1) <= file.getSize()) {
|
||||
// 小于 1M 的
|
||||
try {
|
||||
String fileNames1 = file.getOriginalFilename();
|
||||
File newFile = new File(fileNames1);
|
||||
if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.4f).toFile(newFile);
|
||||
}
|
||||
// 1 - 2M 的
|
||||
else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.2f).toFile(newFile);
|
||||
}
|
||||
// 2M 以上的
|
||||
else if ((1024 * 1024 * 2) < file.getSize()) {
|
||||
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.1f).toFile(newFile);
|
||||
}
|
||||
// 转为 MultipartFile
|
||||
file = PictureUtils.getMultipartFile(newFile);
|
||||
newFile.delete();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
initFlowRules();
|
||||
//上传前进行人脸检测
|
||||
String imgBase64 = MinioUtil.getBase64String(file);
|
||||
checkPhoto(imgBase64);
|
||||
|
||||
// 上传并返回访问地址
|
||||
String fileNames = FileUploadUtils.uploadMinio(file, this.bucketName1, fileName);
|
||||
SysFile sysFile = new SysFile();
|
||||
sysFile.setName(FileUtils.getName(fileNames));
|
||||
fileNames = fileNames.replace(miniourl, miniogwurl);
|
||||
sysFile.setUrl(fileNames);
|
||||
return R.ok(sysFile);
|
||||
} catch (Exception e) {
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验人脸质量是否合格
|
||||
*
|
||||
* @param imgBase64
|
||||
*/
|
||||
private void checkPhoto(String imgBase64) {
|
||||
if (StringUtils.isNotEmpty(imgBase64)) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("imgBase64", imgBase64);
|
||||
String body = HttpUtil.postData(upload, map);
|
||||
log.info("checkPhoto_body:{}", body);
|
||||
JSONObject object = JSONObject.parseObject(body);
|
||||
log.info("返回校验结果:{}", JSON.toJSONString(object));
|
||||
if (501 == object.getInteger("code")) {
|
||||
throw new ServiceException("系统繁忙,请稍后再试!");
|
||||
} else if (200 != object.getInteger("code")) {
|
||||
throw new ServiceException("未检测到人脸信息,请重新上传!");
|
||||
} else if (null != object.getInteger("data") && 90 > object.getInteger("data")) {
|
||||
throw new ServiceException("人脸照片校验不合格,请重新上传!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@PostMapping("uploadMinio2")
|
||||
public R<SysFile> uploadMinio2(MultipartFile file,String fileName, String name)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 上传并返回访问地址
|
||||
String fileNames = FileUploadUtils.uploadMinio(file,this.bucketName1,fileName);
|
||||
SysFile sysFile = new SysFile();
|
||||
sysFile.setName(URLEncoder.encode(name, "UTF-8"));
|
||||
fileNames=fileNames.replace(miniourl,miniogwurl);
|
||||
sysFile.setUrl(fileNames);
|
||||
return R.ok(sysFile);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 文件上传请求
|
||||
*/
|
||||
@GetMapping("compareTwoPic")
|
||||
public R<Float> compareTwoPic(@RequestParam("url1") String url1,@RequestParam("url2") String url2){
|
||||
try
|
||||
{
|
||||
//进行人脸1v1
|
||||
byte[] image1= Base64.decodeBase64(ImageToBase64Utils.getImgUrlToBase64(url1));
|
||||
byte[] image2=Base64.decodeBase64(ImageToBase64Utils.getImgUrlToBase64(url2));
|
||||
float data=faceService.compareTwoPic(image1,image2);
|
||||
return R.ok(data);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传请求
|
||||
*/
|
||||
@GetMapping("comparePic")
|
||||
public R<Float> comparePic(@RequestParam("feature1") String feature1,@RequestParam("feature2") String feature2){
|
||||
try
|
||||
{
|
||||
//进行人脸1v1
|
||||
float data=faceService.compareTwoPic(feature1,feature2);
|
||||
return R.ok(data);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.error("上传文件失败", e);
|
||||
return R.fail(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static void initFlowRules(){
|
||||
List<FlowRule> rules = new ArrayList<>();
|
||||
FlowRule rule = new FlowRule();
|
||||
rule.setResource("HelloWorld");
|
||||
//通过QPS来限流
|
||||
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
|
||||
//设置QPS为20.
|
||||
rule.setCount(10);
|
||||
rule.setLimitApp("default");
|
||||
rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
|
||||
rules.add(rule);
|
||||
FlowRuleManager.loadRules(rules);
|
||||
}
|
||||
|
||||
|
||||
@PostMapping("/deleteFile")
|
||||
public R<String> deleteFile(String fileName) {
|
||||
try {
|
||||
// 创建MinIO客户端
|
||||
MinioClient minioClient = MinioClient.builder()
|
||||
.endpoint(miniourl)
|
||||
.credentials(accessKey, secretKey)
|
||||
.build();
|
||||
|
||||
// 删除文件
|
||||
minioClient.removeObject(RemoveObjectArgs.builder()
|
||||
.bucket(bucketName1) // 替换为你实际的存储桶名称
|
||||
.object(fileName)
|
||||
.build());
|
||||
|
||||
return R.ok("文件删除成功");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return R.fail("文件删除失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.dcsoft.file.controller;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
|
||||
public class test {
|
||||
public static void main(String[] args) throws Exception {
|
||||
MinIO minIO = new MinIO("http://192.168.124.185:9000","minioadmin","minioadmin");
|
||||
String bucket = "visitor";
|
||||
//一、上传文件:
|
||||
//将file转化为MultipartFile (图片在项目的resources目录下,必须将文件转化为为MultipartFile类型)
|
||||
// File file = new File("src/main/resources/img.png");
|
||||
// FileInputStream fileInputStream = new FileInputStream(file);
|
||||
// MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
|
||||
// MediaType.IMAGE_PNG_VALUE //PNG类型的图片,所以用这个枚举。点击MediaType有对应类型
|
||||
// , fileInputStream);
|
||||
// String url = minIO.upload(multipartFile, bucket);//上传
|
||||
// System.out.println("上传之后的URL为:"+url);
|
||||
//二、删除刚刚上传的图片:
|
||||
String fileName = "/insurancePolicy1/1FUe3OV4yKlD41feaef8ea19ed5e94c0749d84dc749320240529153149A026.pdf";
|
||||
minIO.delete(bucket,fileName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.dcsoft.file.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.dcsoft.common.core.exception.ServiceException;
|
||||
import com.dcsoft.file.utils.HttpUtil;
|
||||
import com.dcsoft.file.utils.MinioUtil;
|
||||
import com.dcsoft.file.utils.PictureUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class zctest {
|
||||
|
||||
private static final ExecutorService executorService = Executors.newFixedThreadPool(2);
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
// for (int i = 0; i < 6; i++) {
|
||||
// executorService.execute(connectTcpTask);
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
static Runnable connectTcpTask = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
String filePath = "C:\\Users\\jingy\\Pictures\\test4.jpg";
|
||||
File file = new File(filePath);
|
||||
MultipartFile multipartFile = PictureUtils.getMultipartFile(file);
|
||||
String imgBase64 = null;
|
||||
try {
|
||||
imgBase64 = MinioUtil.getBase64String(multipartFile);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
checkPhoto(imgBase64);
|
||||
}};
|
||||
|
||||
private static void checkPhoto(String imgBase64) {
|
||||
if (StringUtils.isNotEmpty(imgBase64)) {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("imgBase64", imgBase64);
|
||||
String body = HttpUtil.postData("http://81.68.71.142:7701/check/judgeImage", map);
|
||||
JSONObject object = JSONObject.parseObject(body);
|
||||
System.out.println("结果:" + object.toJSONString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.dcsoft.file.service;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.dcsoft.common.core.constant.CacheConstants;
|
||||
import com.dcsoft.common.core.utils.StringUtils;
|
||||
import com.dcsoft.file.utils.HttpUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 用户管理 服务层处理
|
||||
*
|
||||
* @author xueyi
|
||||
*/
|
||||
@Service
|
||||
public class AlgoServiceImpl implements IAlgoService {
|
||||
|
||||
|
||||
@Value("${uni.faceUrl}")
|
||||
public String uniUrl;
|
||||
|
||||
|
||||
//检测图片
|
||||
public String judgeImage(String admitGuids){
|
||||
String url=uniUrl+"/algo/wrapper/judgeImage";
|
||||
Map<String, Object> paramMap=new HashMap<String, Object>();
|
||||
paramMap.put("imageDataBase64",admitGuids);
|
||||
String response= HttpUtil.postData(url,null,paramMap);
|
||||
return response;
|
||||
}
|
||||
|
||||
/* //提取特征值
|
||||
public String getFeature(String admitGuids){
|
||||
String url=uniUrl+"/algo/wrapper/getFeature";
|
||||
Map<String, Object> headMap=new HashMap<String, Object>();
|
||||
Map<String, Object> paramMap=new HashMap<String, Object>();
|
||||
paramMap.put("admitGuids",admitGuids);
|
||||
String response= HttpUtil.postData(url,headMap,paramMap);
|
||||
return response;
|
||||
}
|
||||
|
||||
//图片压缩
|
||||
public String getSimpleImage(String admitGuids){
|
||||
String url=uniUrl+"/algo/wrapper/getSimpleImage";
|
||||
Map<String, Object> headMap=new HashMap<String, Object>();
|
||||
Map<String, Object> paramMap=new HashMap<String, Object>();
|
||||
paramMap.put("admitGuids",admitGuids);
|
||||
String response= HttpUtil.postData(url,headMap,paramMap);
|
||||
return response;
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.dcsoft.file.service;
|
||||
|
||||
import com.dcsoft.file.utils.HttpUtil;
|
||||
import com.dcsoft.file.utils.ImageToBase64Utils;
|
||||
import com.uniubi.Register.FaceBox;
|
||||
import com.uniubi.Register.UfaceRegister;
|
||||
import com.uniubi.Register.UfaceRegisterJNI;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 用户管理 服务层处理
|
||||
*
|
||||
* @author xueyi
|
||||
*/
|
||||
@Service
|
||||
public class FaceServiceImpl implements IFaceService {
|
||||
|
||||
//@Value("${uni.modelPath}")
|
||||
public String modelPath;
|
||||
|
||||
//@Value("${uni.userName}")
|
||||
public String userName;
|
||||
|
||||
//@Value("${uni.passWord}")
|
||||
public String passWord;
|
||||
|
||||
//@Value("${uni.license}")
|
||||
public String license;
|
||||
|
||||
/**
|
||||
* 项目启动时,初始化参数到缓存
|
||||
*/
|
||||
@PostConstruct
|
||||
public void init()
|
||||
{
|
||||
/*System.out.println("SDK version : " + UfaceRegisterJNI.GetSDKVersion());
|
||||
UfaceRegister.SetLogMode(2);
|
||||
UfaceRegister.SetModelPath(modelPath);
|
||||
UfaceRegister.Auth(userName,passWord, license);*/
|
||||
}
|
||||
|
||||
//检测图片
|
||||
public int judgeImageUrl(String url){
|
||||
UfaceRegister u = new UfaceRegister();
|
||||
System.out.println("UfaceRegister : " + u );
|
||||
byte[] image1 = Base64.decodeBase64(ImageToBase64Utils.getImgUrlToBase64(url));
|
||||
FaceBox box1 = new FaceBox();
|
||||
return u.JudgeImage(image1, box1);
|
||||
}
|
||||
|
||||
//检测图片
|
||||
public int judgeImageBase64(String base64){
|
||||
UfaceRegister u = new UfaceRegister();
|
||||
byte[] image1 = Base64.decodeBase64(base64);
|
||||
FaceBox box1 = new FaceBox();
|
||||
return u.JudgeImage(image1, box1);
|
||||
}
|
||||
|
||||
//提取特征值
|
||||
public String getFeature(String base64){
|
||||
UfaceRegister u = new UfaceRegister();
|
||||
byte[] image1 = Base64.decodeBase64(base64);
|
||||
FaceBox box1 = new FaceBox();
|
||||
return u.GetFeature(image1, 110,box1);
|
||||
}
|
||||
|
||||
//图片比对
|
||||
public float compareTwoPic(byte[] image1,byte[] image2){
|
||||
float score=0;
|
||||
UfaceRegister u = new UfaceRegister();
|
||||
FaceBox box1 = new FaceBox();
|
||||
int res1 = u.JudgeImage(image1, box1);
|
||||
String feature1 = "";
|
||||
if (res1 == 0) {
|
||||
feature1 = u.GetFeature(image1, 110, box1);
|
||||
} else {
|
||||
System.out.println("res1 == " + res1);
|
||||
}
|
||||
|
||||
FaceBox box2 = new FaceBox();
|
||||
int res2 = u.JudgeImage(image2, box2);
|
||||
String feature2 = "";
|
||||
if (res2 == 0) {
|
||||
feature2 = u.GetFeature(image2, 110, box2);
|
||||
} else {
|
||||
System.out.println("res2 == " + res2);
|
||||
}
|
||||
score = u.CompareFeat(feature1, feature2);
|
||||
System.out.println("score : " + score);
|
||||
return score;
|
||||
}
|
||||
|
||||
|
||||
//特征值与图片比对
|
||||
public float compareTwoPic(String feature1,String feature2){
|
||||
float score=0;
|
||||
UfaceRegister u = new UfaceRegister();
|
||||
score = u.CompareFeat(feature1, feature2);
|
||||
System.out.println("score : " + score);
|
||||
return score;
|
||||
}
|
||||
|
||||
/*
|
||||
//图片压缩
|
||||
public String getSimpleImage(String admitGuids){
|
||||
String url=uniUrl+"/algo/wrapper/getSimpleImage";
|
||||
Map<String, Object> headMap=new HashMap<String, Object>();
|
||||
Map<String, Object> paramMap=new HashMap<String, Object>();
|
||||
paramMap.put("admitGuids",admitGuids);
|
||||
String response= HttpUtil.postData(url,headMap,paramMap);
|
||||
return response;
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.dcsoft.file.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
|
||||
import com.github.tobato.fastdfs.service.FastFileStorageClient;
|
||||
import com.dcsoft.common.core.utils.file.FileTypeUtils;
|
||||
|
||||
/**
|
||||
* FastDFS 文件存储
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
@Service
|
||||
public class FastDfsSysFileServiceImpl implements ISysFileService
|
||||
{
|
||||
/**
|
||||
* 域名或本机访问地址
|
||||
*/
|
||||
@Value("${fdfs.domain}")
|
||||
public String domain;
|
||||
|
||||
@Autowired
|
||||
private FastFileStorageClient storageClient;
|
||||
|
||||
/**
|
||||
* FastDfs文件上传接口
|
||||
*
|
||||
* @param file 上传的文件
|
||||
* @return 访问地址
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public String uploadFile(MultipartFile file) throws Exception
|
||||
{
|
||||
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
|
||||
FileTypeUtils.getExtension(file), null);
|
||||
return domain + "/" + storePath.getFullPath();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.dcsoft.file.service;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Uface 服务层
|
||||
*
|
||||
* @author nichun
|
||||
*/
|
||||
public interface IAlgoService {
|
||||
|
||||
//检测图片
|
||||
String judgeImage(String url);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.dcsoft.file.service;
|
||||
|
||||
/**
|
||||
* Uface 服务层
|
||||
*
|
||||
* @author nichun
|
||||
*/
|
||||
public interface IFaceService {
|
||||
|
||||
//检测图片
|
||||
int judgeImageUrl(String url);
|
||||
|
||||
//检测图片
|
||||
int judgeImageBase64(String base64);
|
||||
|
||||
//提取特征值
|
||||
String getFeature(String base64);
|
||||
|
||||
float compareTwoPic(byte[] image1,byte[] image2);
|
||||
|
||||
float compareTwoPic(String feature1,String feature2);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.dcsoft.file.service;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* 文件上传接口
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
public interface ISysFileService
|
||||
{
|
||||
/**
|
||||
* 文件上传接口
|
||||
*
|
||||
* @param file 上传的文件
|
||||
* @return 访问地址
|
||||
* @throws Exception
|
||||
*/
|
||||
public String uploadFile(MultipartFile file) throws Exception;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.dcsoft.file.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.dcsoft.file.utils.FileUploadUtils;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
/**
|
||||
* 本地文件存储
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
@Primary
|
||||
@Service
|
||||
public class LocalSysFileServiceImpl implements ISysFileService
|
||||
{
|
||||
/**
|
||||
* 资源映射路径 前缀
|
||||
*/
|
||||
@Value("${file.prefix}")
|
||||
public String localFilePrefix;
|
||||
|
||||
/**
|
||||
* 域名或本机访问地址
|
||||
*/
|
||||
@Value("${file.domain}")
|
||||
public String domain;
|
||||
|
||||
/**
|
||||
* 上传文件存储在本地的根路径
|
||||
*/
|
||||
@Value("${file.path}")
|
||||
private String localFilePath;
|
||||
|
||||
/**
|
||||
* 本地文件上传接口
|
||||
*
|
||||
* @param file 上传的文件
|
||||
* @return 访问地址
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public String uploadFile(MultipartFile file) throws Exception
|
||||
{
|
||||
// InetAddress localHost = InetAddress.getLocalHost();
|
||||
// String ip = localHost.getHostAddress();
|
||||
// String name = FileUploadUtils.upload(localFilePath, file);
|
||||
// String url = "http://127.0.0.1:9300" + localFilePrefix + name;
|
||||
String name = FileUploadUtils.upload(localFilePath, file);
|
||||
String url = domain + localFilePrefix + name;
|
||||
return url;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.dcsoft.file.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.dcsoft.file.config.MinioConfig;
|
||||
import com.dcsoft.file.utils.FileUploadUtils;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectArgs;
|
||||
|
||||
/**
|
||||
* Minio 文件存储
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
@Service
|
||||
public class MinioSysFileServiceImpl implements ISysFileService
|
||||
{
|
||||
@Autowired
|
||||
private MinioConfig minioConfig;
|
||||
|
||||
@Autowired
|
||||
private MinioClient client;
|
||||
|
||||
/**
|
||||
* 本地文件上传接口
|
||||
*
|
||||
* @param file 上传的文件
|
||||
* @return 访问地址
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public String uploadFile(MultipartFile file) throws Exception
|
||||
{
|
||||
String fileName = FileUploadUtils.extractFilename(file);
|
||||
PutObjectArgs args = PutObjectArgs.builder()
|
||||
.bucket(minioConfig.getBucketName())
|
||||
.object(fileName)
|
||||
.stream(file.getInputStream(), file.getSize(), -1)
|
||||
.contentType(file.getContentType())
|
||||
.build();
|
||||
client.putObject(args);
|
||||
return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.dcsoft.file.utils;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class BASE64DecodedMultipartFile implements MultipartFile {
|
||||
|
||||
private final byte[] imgContent;
|
||||
private final String header;
|
||||
|
||||
public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
|
||||
this.imgContent = imgContent;
|
||||
this.header = header.split(";")[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getOriginalFilename() {
|
||||
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
return header.split(":")[1];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return imgContent == null || imgContent.length == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize() {
|
||||
return imgContent.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] getBytes() throws IOException {
|
||||
return imgContent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(imgContent);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transferTo(File dest) throws IOException, IllegalStateException {
|
||||
new FileOutputStream(dest).write(imgContent);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package com.dcsoft.file.utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Objects;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import com.dcsoft.common.core.exception.file.FileNameLengthLimitExceededException;
|
||||
import com.dcsoft.common.core.exception.file.FileSizeLimitExceededException;
|
||||
import com.dcsoft.common.core.exception.file.InvalidExtensionException;
|
||||
import com.dcsoft.common.core.utils.DateUtils;
|
||||
import com.dcsoft.common.core.utils.StringUtils;
|
||||
import com.dcsoft.common.core.utils.file.FileTypeUtils;
|
||||
import com.dcsoft.common.core.utils.file.MimeTypeUtils;
|
||||
import com.dcsoft.common.core.utils.uuid.Seq;
|
||||
|
||||
/**
|
||||
* 文件上传工具类
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
@Slf4j
|
||||
public class FileUploadUtils
|
||||
{
|
||||
/**
|
||||
* 默认大小 50M
|
||||
*/
|
||||
public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 默认的文件名最大长度 100
|
||||
*/
|
||||
public static final int DEFAULT_FILE_NAME_LENGTH = 100;
|
||||
|
||||
/**
|
||||
* 根据文件路径上传
|
||||
*
|
||||
* @param baseDir 相对应用的基目录
|
||||
* @param file 上传的文件
|
||||
* @return 文件名称
|
||||
* @throws IOException
|
||||
*/
|
||||
public static final String upload(String baseDir, MultipartFile file) throws IOException
|
||||
{
|
||||
try
|
||||
{
|
||||
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new IOException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件上传
|
||||
*
|
||||
* @param baseDir 相对应用的基目录
|
||||
* @param file 上传的文件
|
||||
* @param allowedExtension 上传文件类型
|
||||
* @return 返回上传成功的文件名
|
||||
* @throws FileSizeLimitExceededException 如果超出最大大小
|
||||
* @throws FileNameLengthLimitExceededException 文件名太长
|
||||
* @throws IOException 比如读写文件出错时
|
||||
* @throws InvalidExtensionException 文件校验异常
|
||||
*/
|
||||
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
|
||||
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
|
||||
InvalidExtensionException
|
||||
{
|
||||
int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
|
||||
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
|
||||
{
|
||||
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
|
||||
}
|
||||
|
||||
assertAllowed(file, allowedExtension);
|
||||
|
||||
String fileName = extractFilename(file);
|
||||
|
||||
String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
|
||||
file.transferTo(Paths.get(absPath));
|
||||
return getPathFileName(fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 编码文件名
|
||||
*/
|
||||
public static final String extractFilename(MultipartFile file)
|
||||
{
|
||||
return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
|
||||
FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), FileTypeUtils.getExtension(file));
|
||||
}
|
||||
|
||||
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
|
||||
{
|
||||
File desc = new File(uploadDir + File.separator + fileName);
|
||||
|
||||
if (!desc.exists())
|
||||
{
|
||||
if (!desc.getParentFile().exists())
|
||||
{
|
||||
desc.getParentFile().mkdirs();
|
||||
}
|
||||
}
|
||||
return desc.isAbsolute() ? desc : desc.getAbsoluteFile();
|
||||
}
|
||||
|
||||
private static final String getPathFileName(String fileName) throws IOException
|
||||
{
|
||||
String pathFileName = "/" + fileName;
|
||||
return pathFileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件大小校验
|
||||
*
|
||||
* @param file 上传的文件
|
||||
* @throws FileSizeLimitExceededException 如果超出最大大小
|
||||
* @throws InvalidExtensionException 文件校验异常
|
||||
*/
|
||||
public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
|
||||
throws FileSizeLimitExceededException, InvalidExtensionException
|
||||
{
|
||||
long size = file.getSize();
|
||||
if (size > DEFAULT_MAX_SIZE)
|
||||
{
|
||||
throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
|
||||
}
|
||||
|
||||
String fileName = file.getOriginalFilename();
|
||||
String extension = FileTypeUtils.getExtension(file);
|
||||
if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
|
||||
{
|
||||
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
|
||||
{
|
||||
throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
|
||||
fileName);
|
||||
}
|
||||
else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
|
||||
{
|
||||
throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
|
||||
fileName);
|
||||
}
|
||||
else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
|
||||
{
|
||||
throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
|
||||
fileName);
|
||||
}
|
||||
else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION)
|
||||
{
|
||||
throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
|
||||
fileName);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidExtensionException(allowedExtension, extension, fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断MIME类型是否是允许的MIME类型
|
||||
*
|
||||
* @param extension 上传文件类型
|
||||
* @param allowedExtension 允许上传文件类型
|
||||
* @return true/false
|
||||
*/
|
||||
public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
|
||||
{
|
||||
for (String str : allowedExtension)
|
||||
{
|
||||
if (str.equalsIgnoreCase(extension))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 上传到Minio服务器*/
|
||||
public static final String uploadMinio(MultipartFile file,String Name,String fileName) throws IOException
|
||||
{
|
||||
try
|
||||
{
|
||||
String bucketName= Name;
|
||||
return uploadMinino(bucketName,fileName,file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new IOException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 上传前校验方法*/
|
||||
private static final String uploadMinino(String bucketName,String fileName, MultipartFile file, String[] allowedExtension)
|
||||
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
|
||||
InvalidExtensionException
|
||||
{
|
||||
int fileNamelength = file.getOriginalFilename().length();
|
||||
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
|
||||
{
|
||||
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
|
||||
}
|
||||
|
||||
assertAllowed(file, allowedExtension);
|
||||
try {
|
||||
//String fileName = extractFilename(file);//日期格式
|
||||
String suffixName = null;
|
||||
int lastIndex = file.getOriginalFilename().lastIndexOf(".");
|
||||
if (lastIndex != -1 && lastIndex < file.getOriginalFilename().length() - 1) {
|
||||
String extension = file.getOriginalFilename().substring(lastIndex + 1);
|
||||
suffixName = "." + extension;
|
||||
} else {
|
||||
suffixName = ".jpg";
|
||||
}
|
||||
log.info("1111" + suffixName);
|
||||
fileName+="/"+FilenameUtils.getBaseName(file.getOriginalFilename())+ Seq.getId(Seq.uploadSeqType)+suffixName;
|
||||
//调用自定义MinioUtil类方法
|
||||
log.info("bucketName" + bucketName);
|
||||
log.info("fileName" + fileName);
|
||||
String pathFileName = MinioUtil.uploadFile(bucketName, fileName, file);
|
||||
log.info("pathFileName" + pathFileName);
|
||||
return pathFileName;
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
return "";
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package com.dcsoft.file.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
public class HttpUtil {
|
||||
|
||||
public static String getData(String url) {
|
||||
CloseableHttpClient httpClient = null;
|
||||
CloseableHttpResponse response = null;
|
||||
String result = "";
|
||||
try {
|
||||
// 通过址默认配置创建一个httpClient实例
|
||||
httpClient = HttpClients.createDefault();
|
||||
// 创建httpGet远程连接实例
|
||||
HttpGet httpGet = new HttpGet(url);
|
||||
// 设置请求头信息,鉴权
|
||||
httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
|
||||
// 设置配置请求参数
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
|
||||
.setConnectionRequestTimeout(35000)// 请求超时时间
|
||||
.setSocketTimeout(60000)// 数据读取超时时间
|
||||
.build();
|
||||
// 为httpGet实例设置配置
|
||||
httpGet.setConfig(requestConfig);
|
||||
// 执行get请求得到返回对象
|
||||
response = httpClient.execute(httpGet);
|
||||
// 通过返回对象获取返回数据
|
||||
HttpEntity entity = response.getEntity();
|
||||
// 通过EntityUtils中的toString方法将结果转换为字符串
|
||||
result = EntityUtils.toString(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 关闭资源
|
||||
if (null != response) {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (null != httpClient) {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String postData(String url, Map<String, Object> paramMap) {
|
||||
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
|
||||
HttpPost post = new HttpPost(url);
|
||||
String result = "";
|
||||
try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
|
||||
// HttpEntity entity = new StringEntity(jsonStrData);
|
||||
// 修复 POST json 导致中文乱码
|
||||
HttpEntity entity = new StringEntity(JSONObject.toJSONString(paramMap), "UTF-8");
|
||||
post.setEntity(entity);
|
||||
post.setHeader("Content-type", "application/json");
|
||||
HttpResponse resp = closeableHttpClient.execute(post);
|
||||
try {
|
||||
InputStream respIs = resp.getEntity().getContent();
|
||||
byte[] respBytes = IOUtils.toByteArray(respIs);
|
||||
result = new String(respBytes, Charset.forName("UTF-8"));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* form表单提交
|
||||
*
|
||||
* @param url
|
||||
* @param paramMap
|
||||
* @return
|
||||
*/
|
||||
public static String sendxwwwform(String url, Map<String, Object> paramMap) {
|
||||
CloseableHttpClient httpClient = null;
|
||||
CloseableHttpResponse httpResponse = null;
|
||||
String result = "";
|
||||
// 创建httpClient实例
|
||||
httpClient = HttpClients.createDefault();
|
||||
// 创建httpPost远程连接实例
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
// 配置请求参数实例
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
|
||||
.setConnectionRequestTimeout(35000)// 设置连接请求超时时间
|
||||
.setSocketTimeout(60000)// 设置读取数据连接超时时间
|
||||
.build();
|
||||
// 为httpPost实例设置配置
|
||||
httpPost.setConfig(requestConfig);
|
||||
// 设置请求头
|
||||
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
|
||||
// 封装post请求参数
|
||||
if (null != paramMap && paramMap.size() > 0) {
|
||||
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
|
||||
// 通过map集成entrySet方法获取entity
|
||||
Set<Entry<String, Object>> entrySet = paramMap.entrySet();
|
||||
// 循环遍历,获取迭代器
|
||||
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Entry<String, Object> mapEntry = iterator.next();
|
||||
nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
|
||||
}
|
||||
|
||||
// 为httpPost设置封装好的请求参数
|
||||
try {
|
||||
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
try {
|
||||
// httpClient对象执行post请求,并返回响应参数对象
|
||||
httpResponse = httpClient.execute(httpPost);
|
||||
// 从响应对象中获取响应内容
|
||||
HttpEntity entity = httpResponse.getEntity();
|
||||
result = EntityUtils.toString(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 关闭资源
|
||||
if (null != httpResponse) {
|
||||
try {
|
||||
httpResponse.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (null != httpClient) {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String getUrl(String url,Map<String, Object> headMap,String projectGuid ) {
|
||||
CloseableHttpClient httpClient = null;
|
||||
CloseableHttpResponse response = null;
|
||||
String result = "";
|
||||
try {
|
||||
// 通过址默认配置创建一个httpClient实例
|
||||
httpClient = HttpClients.createDefault();
|
||||
// 创建httpGet远程连接实例
|
||||
StringBuffer sb = new StringBuffer(url);
|
||||
sb.append("projectGuid=" + projectGuid);
|
||||
HttpGet httpGet = new HttpGet(sb.toString());
|
||||
// 设置请求头信息,鉴权
|
||||
httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
|
||||
httpGet.setHeader("appKey",headMap.get("appKey").toString());
|
||||
httpGet.setHeader("timestamp",headMap.get("timestamp").toString());
|
||||
httpGet.setHeader("sign",headMap.get("sign").toString());
|
||||
// 设置配置请求参数
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
|
||||
.setConnectionRequestTimeout(35000)// 请求超时时间
|
||||
.setSocketTimeout(60000)// 数据读取超时时间
|
||||
.build();
|
||||
// 为httpGet实例设置配置
|
||||
httpGet.setConfig(requestConfig);
|
||||
// 执行get请求得到返回对象
|
||||
response = httpClient.execute(httpGet);
|
||||
// 通过返回对象获取返回数据
|
||||
HttpEntity entity = response.getEntity();
|
||||
// 通过EntityUtils中的toString方法将结果转换为字符串
|
||||
result = EntityUtils.toString(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 关闭资源
|
||||
if (null != response) {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (null != httpClient) {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String postData(String url,Map<String, Object> headMap, Map<String, Object> paramMap) {
|
||||
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
|
||||
HttpPost post = new HttpPost(url);
|
||||
String result = "";
|
||||
try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
|
||||
// HttpEntity entity = new StringEntity(jsonStrData);
|
||||
// 修复 POST json 导致中文乱码
|
||||
HttpEntity entity = new StringEntity(JSONObject.toJSONString(paramMap), "UTF-8");
|
||||
post.setEntity(entity);
|
||||
post.setHeader("Content-type", "application/json");
|
||||
if (null != headMap && headMap.size() > 0) {
|
||||
// 通过map集成entrySet方法获取entity
|
||||
Set<Entry<String, Object>> entrySet = headMap.entrySet();
|
||||
// 循环遍历,获取迭代器
|
||||
Iterator<Entry<String, Object>> iterator = entrySet.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Entry<String, Object> mapEntry = iterator.next();
|
||||
post.setHeader(mapEntry.getKey(),mapEntry.getValue().toString());
|
||||
}
|
||||
}
|
||||
HttpResponse resp = closeableHttpClient.execute(post);
|
||||
try {
|
||||
InputStream respIs = resp.getEntity().getContent();
|
||||
byte[] respBytes = IOUtils.toByteArray(respIs);
|
||||
result = new String(respBytes, Charset.forName("UTF-8"));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.dcsoft.file.utils;
|
||||
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
|
||||
public class ImageToBase64Utils {
|
||||
/**
|
||||
* 本地图片转base64
|
||||
*/
|
||||
public static String getImgFileToBase642(String imgFile) {
|
||||
//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
|
||||
byte[] buffer = null;
|
||||
//读取图片字节数组
|
||||
try(InputStream inputStream = new FileInputStream(imgFile);){
|
||||
int count = 0;
|
||||
while (count == 0) {
|
||||
count = inputStream.available();
|
||||
}
|
||||
buffer = new byte[count];
|
||||
inputStream.read(buffer);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
// 对字节数组Base64编码
|
||||
return new String(Base64.encodeBase64(buffer));
|
||||
}
|
||||
|
||||
/**
|
||||
* 网络图片转base64
|
||||
*/
|
||||
public static String getImgUrlToBase64(String imgUrl) {
|
||||
byte[] buffer = null;
|
||||
InputStream inputStream = null;
|
||||
try (
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();){
|
||||
// 创建URL
|
||||
URL url = new URL(imgUrl);
|
||||
// 创建链接
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(5000);
|
||||
inputStream = conn.getInputStream();
|
||||
// 将内容读取内存中
|
||||
buffer = new byte[1024];
|
||||
int len = -1;
|
||||
while ((len = inputStream.read(buffer)) != -1) {
|
||||
outputStream.write(buffer, 0, len);
|
||||
}
|
||||
buffer = outputStream.toByteArray();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
// 关闭inputStream流
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 对字节数组Base64编码
|
||||
return new String(Base64.encodeBase64(buffer));
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地或网络图片转base64
|
||||
*/
|
||||
public static String getImgStrToBase64(String imgStr) {
|
||||
InputStream inputStream = null;
|
||||
byte[] buffer = null;
|
||||
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();){
|
||||
//判断网络链接图片文件/本地目录图片文件
|
||||
if (imgStr.startsWith("http://") || imgStr.startsWith("https://")) {
|
||||
// 创建URL
|
||||
URL url = new URL(imgStr);
|
||||
// 创建链接
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(5000);
|
||||
inputStream = conn.getInputStream();
|
||||
// 将内容读取内存中
|
||||
buffer = new byte[1024];
|
||||
int len = -1;
|
||||
while ((len = inputStream.read(buffer)) != -1) {
|
||||
outputStream.write(buffer, 0, len);
|
||||
}
|
||||
buffer = outputStream.toByteArray();
|
||||
} else {
|
||||
inputStream = new FileInputStream(imgStr);
|
||||
int count = 0;
|
||||
while (count == 0) {
|
||||
count = inputStream.available();
|
||||
}
|
||||
buffer = new byte[count];
|
||||
inputStream.read(buffer);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
// 关闭inputStream流
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 对字节数组Base64编码
|
||||
|
||||
return new String(Base64.encodeBase64(buffer));
|
||||
}
|
||||
|
||||
/**
|
||||
* 对字节数组字符串进行Base64解码并生成图片
|
||||
* @param imgStr 图片数据
|
||||
* @param imgFilePath 保存图片全路径地址
|
||||
* @return
|
||||
*/
|
||||
public static boolean generateImage(String imgStr,String imgFilePath){
|
||||
//
|
||||
if (imgStr == null) //图像数据为空
|
||||
return false;
|
||||
try
|
||||
{
|
||||
//Base64解码
|
||||
byte[] b = Base64.decodeBase64(imgStr);
|
||||
for(int i=0;i<b.length;++i)
|
||||
{
|
||||
if(b[i]<0)
|
||||
{//调整异常数据
|
||||
b[i]+=256;
|
||||
}
|
||||
}
|
||||
//生成jpeg图片
|
||||
OutputStream out = new FileOutputStream(imgFilePath);
|
||||
out.write(b);
|
||||
out.flush();
|
||||
out.close();
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.dcsoft.file.utils;
|
||||
|
||||
import com.dcsoft.common.core.exception.file.FileNameLengthLimitExceededException;
|
||||
import com.dcsoft.common.core.exception.file.FileSizeLimitExceededException;
|
||||
import com.dcsoft.common.core.exception.file.InvalidExtensionException;
|
||||
import com.dcsoft.common.core.utils.DateUtils;
|
||||
import com.dcsoft.common.core.utils.SpringUtils;
|
||||
import com.dcsoft.common.core.utils.StringUtils;
|
||||
import com.dcsoft.common.core.utils.file.FileTypeUtils;
|
||||
import com.dcsoft.common.core.utils.file.MimeTypeUtils;
|
||||
import com.dcsoft.common.core.utils.uuid.Seq;
|
||||
import io.minio.*;
|
||||
import io.minio.http.Method;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import sun.misc.BASE64Encoder;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 文件上传工具类
|
||||
*
|
||||
* @author dcsoft
|
||||
*/
|
||||
/** 初始化了连接方法,及桶权限获取*/
|
||||
public class MinioUtil {
|
||||
/**
|
||||
* @param bucketName 桶名称
|
||||
* @param fileName
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String uploadFile(String bucketName,String fileName,MultipartFile multipartFile) throws IOException
|
||||
{
|
||||
String url = "";
|
||||
MinioClient minioClient = SpringUtils.getBean(MinioClient.class);
|
||||
try (InputStream inputStream = multipartFile.getInputStream()) {
|
||||
boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
|
||||
if (!found)
|
||||
{
|
||||
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
|
||||
/**
|
||||
* bucket权限-读写
|
||||
*/
|
||||
String READ_WRITE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
|
||||
minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(READ_WRITE).build());
|
||||
}
|
||||
minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
|
||||
.object(fileName)
|
||||
.stream(inputStream, multipartFile.getSize(), -1)
|
||||
.contentType(multipartFile.getContentType()).build()
|
||||
);
|
||||
//路径获取
|
||||
url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(fileName).
|
||||
method(Method.GET).build());
|
||||
url = url.substring(0,url.indexOf('?'));
|
||||
//常规访问路径获取
|
||||
return url;
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String getBase64String(MultipartFile multiPartFile) throws IOException {
|
||||
String baseStr = null;
|
||||
BASE64Encoder encoder = new BASE64Encoder();
|
||||
baseStr= encoder.encode(multiPartFile.getBytes());
|
||||
baseStr = baseStr.replaceAll("\r\n", "");
|
||||
return baseStr;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.dcsoft.file.utils;
|
||||
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.fileupload.FileItem;
|
||||
import org.apache.commons.fileupload.FileItemFactory;
|
||||
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.poi.util.IOUtils;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.commons.CommonsMultipartFile;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
//java将图片的url转换成File,File转换成二进制流byte
|
||||
public class PictureUtils {
|
||||
//将Url转换为File
|
||||
public static File UrltoFile(String url) throws Exception {
|
||||
HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
|
||||
httpUrl.connect();
|
||||
InputStream ins=httpUrl.getInputStream();
|
||||
File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "xie.jpg");//System.getProperty("java.io.tmpdir")缓存
|
||||
if (file.exists()) {
|
||||
file.delete();//如果缓存中存在该文件就删除
|
||||
}
|
||||
OutputStream os = new FileOutputStream(file);
|
||||
int bytesRead;
|
||||
int len = 8192;
|
||||
byte[] buffer = new byte[len];
|
||||
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
|
||||
os.write(buffer, 0, bytesRead);
|
||||
}
|
||||
os.close();
|
||||
ins.close();
|
||||
return file;
|
||||
|
||||
}
|
||||
//将File对象转换为byte[]的形式
|
||||
public static byte[] FileTobyte(File file){
|
||||
FileInputStream fileInputStream = null;
|
||||
byte[] imgData = null;
|
||||
|
||||
try {
|
||||
|
||||
imgData = new byte[(int) file.length()];
|
||||
|
||||
//read file into bytes[]
|
||||
fileInputStream = new FileInputStream(file);
|
||||
fileInputStream.read(imgData);
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (fileInputStream != null) {
|
||||
try {
|
||||
fileInputStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return imgData;
|
||||
}
|
||||
|
||||
/**
|
||||
* url转变为 MultipartFile对象
|
||||
* @param url 网络地址链接
|
||||
* @param fileName 文件名
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static MultipartFile createMultipartFile(String url, String fileName){
|
||||
FileItem item = null;
|
||||
CommonsMultipartFile commonsMultipartFile = null;
|
||||
try {
|
||||
//HttpURLconnection是基于http协议的,支持get,post,put,delete等各种请求方式,最常用的就是get和post 这里是根据url发起一个HTTP请求
|
||||
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
conn.setReadTimeout(30000); //设置从主机读取数据超时(单位:毫秒)
|
||||
conn.setConnectTimeout(30000); //设置连接主机超时(单位:毫秒)
|
||||
//设置应用程序要从网络连接读取数据
|
||||
conn.setDoInput(true); //允许读入
|
||||
conn.setRequestMethod("GET"); //设置请求方式为GET
|
||||
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { //发起请求并获取响应码比对。
|
||||
//得到响应流
|
||||
InputStream is = conn.getInputStream();
|
||||
//采用参数指定临界值和系统临时文件夹构造文件项工厂对象。
|
||||
FileItemFactory factory = new DiskFileItemFactory(16, null);
|
||||
String textFieldName = "uploadfile";
|
||||
//根据DiskFileItemFactory相关配置将每一个请求消息实体项目创建成DiskFileItem 实例
|
||||
item = factory.createItem(textFieldName, ContentType.APPLICATION_OCTET_STREAM.toString(), false, fileName);
|
||||
OutputStream os = item.getOutputStream();
|
||||
|
||||
int bytesRead = 0;
|
||||
byte[] buffer = new byte[8192];
|
||||
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
|
||||
os.write(buffer, 0, bytesRead);
|
||||
}
|
||||
|
||||
// 转换为MultipartFile对象
|
||||
commonsMultipartFile = new CommonsMultipartFile(item);
|
||||
os.close();
|
||||
is.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("文件下载失败", e);
|
||||
}
|
||||
|
||||
return commonsMultipartFile ;
|
||||
}
|
||||
|
||||
//File转MultipartFile
|
||||
public static MultipartFile getMultipartFile(File file) {
|
||||
FileItem item = new DiskFileItemFactory().createItem("file"
|
||||
, MediaType.MULTIPART_FORM_DATA_VALUE
|
||||
, true
|
||||
, file.getName());
|
||||
try (InputStream input = new FileInputStream(file);
|
||||
OutputStream os = item.getOutputStream()) {
|
||||
// 流转移
|
||||
IOUtils.copy(input, os);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("Invalid file: " + e, e);
|
||||
}
|
||||
|
||||
return new CommonsMultipartFile(item);
|
||||
}
|
||||
|
||||
|
||||
//二进制文件转换MultipartFile
|
||||
public static MultipartFile getMultipartFile(String name, byte[] bytes) {
|
||||
MultipartFile mfile = null;
|
||||
ByteArrayInputStream in = null;
|
||||
try {
|
||||
in = new ByteArrayInputStream(bytes);
|
||||
FileItemFactory factory = new DiskFileItemFactory(16, null);
|
||||
FileItem fileItem = factory.createItem("mainFile", ContentType.APPLICATION_OCTET_STREAM.toString(), false, name);
|
||||
IOUtils.copy(new ByteArrayInputStream(bytes), fileItem.getOutputStream());
|
||||
mfile = new CommonsMultipartFile(fileItem);
|
||||
in.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return mfile;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.dcsoft.file.utils;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* @Description 透明背景上色
|
||||
* @author 小帅丶
|
||||
* @className PngColoringUtil
|
||||
* @Date 2019/10/11-17:03
|
||||
**/
|
||||
public class PngColoringUtil {
|
||||
/**
|
||||
* @Description 给PNG图片增加背景色
|
||||
* @Author 小帅丶
|
||||
* @param sourceImage 原始图片 最好是PNG透明的
|
||||
* @param targetImage 修改后的图片
|
||||
* @param backgroudColor 背景色
|
||||
**/
|
||||
public static void changePNGBackgroudColor(String sourceImage, String targetImage, Color backgroudColor) {
|
||||
try {
|
||||
BufferedImage result = changePNGBackgroudColor(sourceImage, backgroudColor);
|
||||
File output = new File(targetImage);
|
||||
ImageIO.write(result, "jpg", output);
|
||||
} catch (IOException e) {
|
||||
System.out.println("有问题了" + e.getMessage());
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @Description 给PNG图片增加背景色 返回base64
|
||||
* @Author 小帅丶
|
||||
* @param sourceImage 原始图片 最好是PNG透明的
|
||||
* @param backgroudColor 背景色
|
||||
* @return java.lang.String
|
||||
**/
|
||||
public static String changePNGBackgroudColorByBase64(String sourceImage, Color backgroudColor){
|
||||
try {
|
||||
String base64 = "";
|
||||
BufferedImage result = changePNGBackgroudColor(sourceImage, backgroudColor);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ImageIO.write(result, "jpg", baos );
|
||||
baos.flush();
|
||||
byte[] imageInByte = baos.toByteArray();
|
||||
baos.close();
|
||||
final Base64.Encoder encoder = Base64.getEncoder();
|
||||
base64 = encoder.encodeToString(imageInByte);
|
||||
return base64;
|
||||
}catch (Exception e){
|
||||
System.out.println("有问题了" + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @Description 给PNG图片增加背景色 返回BufferedImage
|
||||
* @Author 小帅丶
|
||||
* @param sourceImage 原始图片 最好是PNG透明的
|
||||
* @param backgroudColor 背景色
|
||||
* @return BufferedImage
|
||||
**/
|
||||
public static BufferedImage changePNGBackgroudColor(String sourceImage, Color backgroudColor) {
|
||||
try {
|
||||
File input = new File(sourceImage);
|
||||
BufferedImage image = ImageIO.read(input);
|
||||
|
||||
BufferedImage result = new BufferedImage(
|
||||
image.getWidth(),
|
||||
image.getHeight(),
|
||||
BufferedImage.TYPE_INT_RGB);
|
||||
|
||||
Graphics2D graphic = result.createGraphics();
|
||||
graphic.drawImage(image, 0, 0, backgroudColor, null);
|
||||
graphic.dispose();
|
||||
return result;
|
||||
} catch (IOException e) {
|
||||
System.out.println("有问题了" + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception{
|
||||
String path="D:\\test";
|
||||
File file1 = new File(path);
|
||||
if (file1.exists()) {
|
||||
File[] files = file1.listFiles();
|
||||
for (File file2:files){
|
||||
String image= String.valueOf(file2.toPath());
|
||||
String resultImage =image.split("\\.")[0]+".jpg";
|
||||
changePNGBackgroudColor(image,resultImage, Color.blue);//原图 目标图 背景色*/
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.uniubi.Register;
|
||||
|
||||
public class FaceBox {
|
||||
public int code;
|
||||
|
||||
public int xmin;
|
||||
public int ymin;
|
||||
public int xmax;
|
||||
public int ymax;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.uniubi.Register;
|
||||
|
||||
public class UfaceRegister {
|
||||
private long handle;
|
||||
|
||||
public enum Status{
|
||||
AUTH_INVALID_PASSWORD(-9, "AUTH_INVALID_PASSWORD"), // 授权验证账号用户名或者密码错误
|
||||
AUTH_RESPONSE_PARSE_FAIL(-8,"AUTH_RESPONSE_PARSE_FAIL"), // 远程返回内容解析失败
|
||||
AUTH_WRITE_NO_PERMISSION(-7,"AUTH_WRITE_NO_PERMISSION"), // lic文件保存失败(设定路径无写入权限)
|
||||
AUTH_INFO_COMPARE_FAIL(-6,"AUTH_INFO_COMPARE_FAIL"), // 硬件信息比对失败(lic文件直接拷贝至其他设备使用)
|
||||
AUTH_LACK_OF_TIMES(-5,"AUTH_LACK_OF_TIMES"), // 授权申请次数已用尽
|
||||
AUTH_GET_INFO_FAIL(-4,"AUTH_GET_INFO_FAIL"), // 获取本地硬件信息失败
|
||||
INIT_FAILED(-3,"INIT_FAILED"), // 初始化失败
|
||||
IMAGE_EMPTY(-2,"IMAGE_EMPTY"), // 图片为空
|
||||
IMAGE_DECODE_FAILED(-1,"IMAGE_DECODE_FAILED"), // 图片解码失败
|
||||
SUCCESS (0,"SUCCESS"), // 成功
|
||||
|
||||
NO_FACE_DETECTED(1,"NO_FACE_DETECTED"), // 未检测到面部
|
||||
FACE_BOX_MULTIPLE(2,"FACE_BOX_MULTIPLE"), // 有多个面部
|
||||
FACE_BOX_TOO_SMALL(3,"FACE_BOX_TOO_SMALL"), // 面部过小
|
||||
FACE_BOX_OUT_OF_RANGE(4,"FACE_BOX_OUT_OF_RANGE"), // 面部越界
|
||||
FACE_PITCH_INVALID(5,"FACE_PITCH_INVALID") , // 面部俯仰角(上下点头)过大
|
||||
FACE_YAW_INVALID(6,"FACE_YAW_INVALID"), // 面部偏航角(左右转头)过大
|
||||
FACE_ROLL_INVALID(7,"FACE_ROLL_INVALID"), // 面部翻滚角(左右歪头)过大
|
||||
FACE_TOO_BRIGHT(8,"FACE_TOO_BRIGHT"), // 面部亮度过亮
|
||||
FACE_TOO_DARK(9,"FACE_TOO_DARK"), // 面部亮度过暗
|
||||
FACE_TOO_BLUR (10,"FACE_TOO_BLUR"), // 面部模糊
|
||||
FACE_ILLUMINATION_UNEVEN(11,"FACE_ILLUMINATION_UNEVEN"), // 面部光照不均匀
|
||||
FACE_ORIENTATION_INVALID(12,"FACE_ORIENTATION_INVALID"), // 面部朝向不对
|
||||
FACE_CLASS_INVALID(13,"FACE_CLASS_INVALID"), // 非正常面部
|
||||
FACE_IS_COVER(14,"FACE_IS_COVER"), // 面部被遮挡
|
||||
FACE_ALMIGHTY_FACE(15,"FACE_ALMIGHTY_FACE"), // 万能人脸
|
||||
INPUT_INVALID_BOX(16,"INPUT_INVALID_BOX"), // 输入框无效
|
||||
LOAD_MODEL_FAILED(17,"LOAD_MODEL_FAILED"), // 加载模型失败
|
||||
CONFIG_FILE_INVALID(18,"CONFIG_FILE_INVALID"), // 配置文件无效
|
||||
;
|
||||
|
||||
private Integer code;
|
||||
private String message;
|
||||
|
||||
Status(Integer code, String message) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static int Auth(String userName, String password, String license) {
|
||||
|
||||
return UfaceRegisterJNI.Auth(userName, password, license);
|
||||
}
|
||||
|
||||
public static String GetSDKVersion() {
|
||||
return UfaceRegisterJNI.GetSDKVersion();
|
||||
}
|
||||
|
||||
public static void SetLogMode(int log_mode) {
|
||||
UfaceRegisterJNI.SetLogMode(log_mode);
|
||||
}
|
||||
|
||||
public static void SetModelPath(String model_path) {
|
||||
UfaceRegisterJNI.SetModelPath(model_path);
|
||||
}
|
||||
|
||||
public UfaceRegister() {
|
||||
handle = UfaceRegisterJNI.NewRegister();
|
||||
}
|
||||
|
||||
public void release() {
|
||||
if (handle == 0) {
|
||||
return;
|
||||
}
|
||||
UfaceRegisterJNI.ReleaseRegister(handle);
|
||||
handle = 0;
|
||||
}
|
||||
|
||||
|
||||
public int JudgeImage(byte[] image_data, FaceBox box) {
|
||||
if (handle == 0) {
|
||||
return -1;
|
||||
}
|
||||
return UfaceRegisterJNI.JudgeImage(handle, image_data, box) ;
|
||||
|
||||
}
|
||||
|
||||
public byte[] GetSimpleImage(byte[] image_data, FaceBox box,int resize_mode,int save_size) {
|
||||
if (handle == 0) {
|
||||
return null;
|
||||
}
|
||||
return UfaceRegisterJNI.GetSimpleImage(handle, image_data, box,resize_mode,save_size);
|
||||
}
|
||||
|
||||
public String GetFeature(byte[] image_data, int feature_version, FaceBox box) {
|
||||
if (handle == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return UfaceRegisterJNI.GetFeature(handle, image_data, feature_version, box);
|
||||
|
||||
}
|
||||
public float DynamicQuality(byte[] image_data, FaceBox box) {
|
||||
if (handle == 0) {
|
||||
return -1;
|
||||
}
|
||||
return UfaceRegisterJNI.DynamicQuality(handle, image_data, box) ;
|
||||
|
||||
}
|
||||
public float CompareFeat(String featA,String featB){
|
||||
if (handle == 0) {
|
||||
return -1;
|
||||
}
|
||||
return UfaceRegisterJNI.CompareFeat(handle,featA,featB);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.uniubi.Register;
|
||||
|
||||
public class UfaceRegisterJNI {
|
||||
|
||||
static {
|
||||
System.out.println("load libuface4_register_jni.so");
|
||||
System.load("/root/lib/libuface4_register_jni.so");
|
||||
}
|
||||
|
||||
public static native int Auth(String usr_name, String usr_pwd, String license_file);
|
||||
|
||||
public static native String GetSDKVersion();
|
||||
|
||||
public static native void SetLogMode(int log_mode);
|
||||
|
||||
public static native void SetModelPath(String model_path);
|
||||
|
||||
public static native long NewRegister();
|
||||
|
||||
public static native void ReleaseRegister(long handle);
|
||||
|
||||
public static native int JudgeImage(long handle, byte[] image_data, FaceBox box);
|
||||
|
||||
public static native byte[] GetSimpleImage(long handle, byte[] image_data, FaceBox box,int resize_mode,int save_size);
|
||||
|
||||
public static native String GetFeature(long handle, byte[] image_data, int feature_version, FaceBox box);
|
||||
|
||||
public static native float DynamicQuality(long handle, byte[] image_data, FaceBox box);
|
||||
|
||||
public static native float CompareFeat(long handle, String featA,String featB);
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user