前端各种图片格式转化为本地File文件
public class ImageFileUtil {
private static final Logger logger = LoggerFactory.getLogger(ImageFileUtil.class);
/**
* multipartFile转本地文件
*
* @param multipartFile
* @param filePath
* @return
*/
public static File getFileByMultipartFile(MultipartFile multipartFile, String filePath) throws IOException {
File file;
String name;
do {
name = "" + System.currentTimeMillis() + RandomStringUtils.randomNumeric(5) + "." + "jpg";
file = new File(filePath, name);
} while (file.exists());
multipartFile.transferTo(file);
return file;
}
/**
* 根据url获取本地图片
*
* @param fileUrl
* @param filePath
* @return
* @throws IOException
*/
public static File getFileByUrl(String fileUrl, String filePath) throws IOException {
File file;
File parentDir = new File(filePath);
if (!parentDir.exists()) {
parentDir.mkdirs();
}
String name;
do {
name = "" + System.currentTimeMillis() + RandomStringUtils.randomNumeric(5) + "." + "jpg";
file = new File(parentDir, name);
} while (file.exists());
URL imageUrl = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
try (InputStream inputStream = conn.getInputStream();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
) {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
stream.write(outStream.toByteArray());
} catch (Exception e) {
throw new RuntimeException("创建人脸获取服务器图片异常");
}
return file;
}
/**
* base64字符串转化成图片
*
* @param base64
* @param filePath
* @return
*/
public static File base64ToFile(String base64, String filePath) {
if (base64.contains("data:image")) {
base64 = base64.substring(base64.indexOf(",") + 1);
}
base64 = base64.replace("\r\n", "");
File file;
//创建文件目录
File parentDir = new File(filePath);
if (!parentDir.exists()) {
parentDir.mkdirs();
}
String name;
do {
name = "" + System.currentTimeMillis() + RandomStringUtils.randomNumeric(5) + "." + "jpg";
file = new File(parentDir, name);
} while (file.exists());
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(base64);
bos.write(bytes);
} catch (Exception e) {
throw new RuntimeException("创建人脸获取服务器图片异常");
}
return file;
}
}