Commit 9c92af97 by songxiang

OSS增加图片裁剪方法同时持久化

parent 0a626b44
...@@ -290,151 +290,151 @@ public class FileUtils { ...@@ -290,151 +290,151 @@ public class FileUtils {
return false; return false;
} }
/** /**
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 * 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做
* *
* @param filePath * @param filePath
*/ */
public static boolean creatDir(String filePath) { public static boolean creatDir(String filePath) {
if (StringUtil.isEmpty(filePath)) { if (StringUtil.isEmpty(filePath)) {
return false; return false;
} }
File file = new File(filePath); File file = new File(filePath);
if (!file.exists()) { if (!file.exists()) {
file.mkdir(); file.mkdir();
return true; return true;
} }
return false; return false;
} }
/** /**
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 该方法能够实现创建整个路径 * 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 该方法能够实现创建整个路径
* *
* @param filePath * @param filePath
*/ */
public static boolean creatDirs(String filePath) { public static boolean creatDirs(String filePath) {
if (StringUtil.isEmpty(filePath)) { if (StringUtil.isEmpty(filePath)) {
return false; return false;
} }
File file = new File(filePath); File file = new File(filePath);
if (!file.exists()) { if (!file.exists()) {
file.mkdirs(); file.mkdirs();
return true; return true;
} }
return false; return false;
} }
/** /**
* 获取文件类型 * 获取文件类型
* *
* @param filePath * @param filePath
*/ */
public static String getFileType(String filePath) { public static String getFileType(String filePath) {
if (StringUtil.isEmpty(filePath)) { if (StringUtil.isEmpty(filePath)) {
return null; return null;
} }
int index1 = filePath.lastIndexOf("."); int index1 = filePath.lastIndexOf(".");
if (index1 < 1) { if (index1 < 1) {
return null; return null;
} }
int index2 = filePath.lastIndexOf("?"); int index2 = filePath.lastIndexOf("?");
if (index2 > index1) { if (index2 > index1) {
filePath = filePath.substring(0, filePath.lastIndexOf("?")); filePath = filePath.substring(0, filePath.lastIndexOf("?"));
} }
filePath = filePath.replace("/", OSConstant.SEPARATOR); filePath = filePath.replace("/", OSConstant.SEPARATOR);
int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR); int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR);
if (index3 > index1) { if (index3 > index1) {
return null; return null;
} }
return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase(); return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase();
} }
/** /**
* 获取文件名称 * 获取文件名称
* *
* @param filePath * @param filePath
*/ */
public static String getFileName(String filePath) { public static String getFileName(String filePath) {
if (StringUtil.isEmpty(filePath)) { if (StringUtil.isEmpty(filePath)) {
return null; return null;
} }
String fileName = null; String fileName = null;
filePath = filePath.replace("/", OSConstant.SEPARATOR); filePath = filePath.replace("/", OSConstant.SEPARATOR);
int index1 = filePath.lastIndexOf("."); int index1 = filePath.lastIndexOf(".");
if (index1 > -1) { if (index1 > -1) {
int index2 = filePath.lastIndexOf("?"); int index2 = filePath.lastIndexOf("?");
if (index2 > index1) { if (index2 > index1) {
filePath = filePath.substring(0, filePath.lastIndexOf("?")); filePath = filePath.substring(0, filePath.lastIndexOf("?"));
} }
int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR); int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR);
if (index3 > index1) { if (index3 > index1) {
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1); fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1);
} else { } else {
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1, fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1,
filePath.lastIndexOf(".")); filePath.lastIndexOf("."));
} }
} else { } else {
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1); fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1);
} }
return formatName(fileName); return formatName(fileName);
} }
/** /**
* 获取文件名称包括后缀 * 获取文件名称包括后缀
* *
* @param filePath * @param filePath
* @return * @return
*/ */
public static String getFileNameAll(String filePath) { public static String getFileNameAll(String filePath) {
if (StringUtil.isEmpty(filePath)) { if (StringUtil.isEmpty(filePath)) {
return null; return null;
} }
String fileName = getFileName(filePath); String fileName = getFileName(filePath);
if (StringUtil.isEmpty(fileName)) { if (StringUtil.isEmpty(fileName)) {
return null; return null;
} }
String fileType = getFileType(filePath); String fileType = getFileType(filePath);
return StringUtil.isEmpty(fileType) ? fileName : fileName + "." + fileType; return StringUtil.isEmpty(fileType) ? fileName : fileName + "." + fileType;
} }
/** /**
* 格式化文件名称,过滤特殊字符(名称太长进行截断) * 格式化文件名称,过滤特殊字符(名称太长进行截断)
* *
* @param fileName * @param fileName
*/ */
public static String formatName(String fileName) { public static String formatName(String fileName) {
if (StringUtil.isEmpty(fileName)) { if (StringUtil.isEmpty(fileName)) {
return null; return null;
} }
try { try {
String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]"; String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]";
Pattern p = Pattern.compile(regEx); Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(fileName); Matcher m = p.matcher(fileName);
String result = m.replaceAll("").trim(); String result = m.replaceAll("").trim();
// 文件名称过长的话,限制40个字 // 文件名称过长的话,限制40个字
return result.length() > 40 ? result.substring(0, 40) : result; return result.length() > 40 ? result.substring(0, 40) : result;
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【文件API】格式化文件名称.[formatName]:" + e.getMessage(), e); LOGGER.error("【文件API】格式化文件名称.[formatName]:" + e.getMessage(), e);
return UUIDUitl.taskName(); return UUIDUitl.taskName();
} }
} }
/** /**
* 获取文件所在的目录 * 获取文件所在的目录
* *
* @param filePath * @param filePath
* @return * @return
*/ */
public static String getFileFolder(String filePath) { public static String getFileFolder(String filePath) {
if (StringUtil.isEmpty(filePath)) { if (StringUtil.isEmpty(filePath)) {
return null; return null;
} }
return filePath.substring(0, filePath.lastIndexOf(OSConstant.SEPARATOR)); return filePath.substring(0, filePath.lastIndexOf(OSConstant.SEPARATOR));
} }
/** /**
* 获取http文件路径的域名 * 获取http文件路径的域名
* *
* @param fileUrl * @param fileUrl
* @return * @return
*/ */
...@@ -450,415 +450,425 @@ public class FileUtils { ...@@ -450,415 +450,425 @@ public class FileUtils {
return null; return null;
} }
/** /**
* FileUtils工具 File @throws * FileUtils工具 File @throws
*/ */
public static File copyURLToFile(String url, String dir) throws Exception { public static File copyURLToFile(String url, String dir) throws Exception {
try { try {
URL httpurl = new URL(url); URL httpurl = new URL(url);
File f = new File(dir); File f = new File(dir);
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f); org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
return f; return f;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
/** /**
* 根据路径删除指定的目录或文件,无论存在与否 * 根据路径删除指定的目录或文件,无论存在与否
* *
* @param sPath 要删除的目录或文件 * @param sPath
* @return 删除成功返回 true,否则返回 false。 * 要删除的目录或文件
*/ * @return 删除成功返回 true,否则返回 false。
public static boolean deleteFolder(String sPath) { */
if (StringUtil.isEmpty(sPath)) { public static boolean deleteFolder(String sPath) {
return false; if (StringUtil.isEmpty(sPath)) {
} return false;
boolean flag = false; }
File file = new File(sPath); boolean flag = false;
// 判断目录或文件是否存在 File file = new File(sPath);
if (!file.exists()) { // 不存在返回 false // 判断目录或文件是否存在
return flag; if (!file.exists()) { // 不存在返回 false
} else { return flag;
// 判断是否为文件 } else {
if (file.isFile()) { // 为文件时调用删除文件方法 // 判断是否为文件
return deleteFile(sPath); if (file.isFile()) { // 为文件时调用删除文件方法
} else { // 为目录时调用删除目录方法 return deleteFile(sPath);
return deleteDirectory(sPath); } else { // 为目录时调用删除目录方法
} return deleteDirectory(sPath);
} }
} }
}
/**
* 删除单个文件 /**
* * 删除单个文件
* @param sPath 被删除文件的文件名 *
* @return 单个文件删除成功返回true,否则返回false * @param sPath
*/ * 被删除文件的文件名
public static boolean deleteFile(String sPath) { * @return 单个文件删除成功返回true,否则返回false
if (StringUtil.isEmpty(sPath)) { */
return false; public static boolean deleteFile(String sPath) {
} if (StringUtil.isEmpty(sPath)) {
boolean flag = false; return false;
File file = new File(sPath); }
// 路径为文件且不为空则进行删除 boolean flag = false;
if (file.isFile() && file.exists()) { File file = new File(sPath);
file.delete(); // 路径为文件且不为空则进行删除
flag = true; if (file.isFile() && file.exists()) {
} file.delete();
return flag; flag = true;
} }
return flag;
/** }
* 删除目录(文件夹)以及目录下的文件
* /**
* @param sPath 被删除目录的文件路径 * 删除目录(文件夹)以及目录下的文件
* @return 目录删除成功返回true,否则返回false *
*/ * @param sPath
public static boolean deleteDirectory(String sPath) { * 被删除目录的文件路径
if (StringUtil.isEmpty(sPath)) { * @return 目录删除成功返回true,否则返回false
return false; */
} public static boolean deleteDirectory(String sPath) {
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符 if (StringUtil.isEmpty(sPath)) {
if (!sPath.endsWith(File.separator)) { return false;
sPath = sPath + File.separator; }
} // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
File dirFile = new File(sPath); if (!sPath.endsWith(File.separator)) {
// 如果dir对应的文件不存在,或者不是一个目录,则退出 sPath = sPath + File.separator;
if (!dirFile.exists() || !dirFile.isDirectory()) { }
return false; File dirFile = new File(sPath);
} // 如果dir对应的文件不存在,或者不是一个目录,则退出
boolean flag = true; if (!dirFile.exists() || !dirFile.isDirectory()) {
// 删除文件夹下的所有文件(包括子目录) return false;
File[] files = dirFile.listFiles(); }
for (int i = 0; i < files.length; i++) { boolean flag = true;
// 删除子文件 // 删除文件夹下的所有文件(包括子目录)
if (files[i].isFile()) { File[] files = dirFile.listFiles();
flag = deleteFile(files[i].getAbsolutePath()); for (int i = 0; i < files.length; i++) {
if (!flag) // 删除子文件
break; if (files[i].isFile()) {
} // 删除子目录 flag = deleteFile(files[i].getAbsolutePath());
else { if (!flag)
flag = deleteDirectory(files[i].getAbsolutePath()); break;
if (!flag) } // 删除子目录
break; else {
} flag = deleteDirectory(files[i].getAbsolutePath());
} if (!flag)
if (!flag) break;
return false; }
// 删除当前目录 }
if (dirFile.delete()) { if (!flag)
return true; return false;
} else { // 删除当前目录
return false; if (dirFile.delete()) {
} return true;
} } else {
return false;
/** }
* 检查文件是否存在 }
*
* @param filePath /**
* @return * 检查文件是否存在
*/ *
public static boolean checkFile(String filePath) { * @param filePath
if (StringUtil.isEmpty(filePath)) { * @return
return false; */
} public static boolean checkFile(String filePath) {
File file = new File(filePath); if (StringUtil.isEmpty(filePath)) {
if (!file.isFile()) { return false;
return false; }
} File file = new File(filePath);
return true; if (!file.isFile()) {
} return false;
}
/** return true;
* | FileUtils工具 }
*/
public static void downloadFileFromUrl(String url, String localFilePath) throws FileException { /**
LOGGER.info("【文件API】下载文件[本地文件].<START>.[url]=" + url + ",[localFilePath]=" + localFilePath); * | FileUtils工具
creatFiles(localFilePath); */
try { public static void downloadFileFromUrl(String url, String localFilePath) throws FileException {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) { LOGGER.info("【文件API】下载文件[本地文件].<START>.[url]=" + url + ",[localFilePath]=" + localFilePath);
OssUtils.downloadFile(url, localFilePath); creatFiles(localFilePath);
// } else if (url.contains("/group")) { try {
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url); if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value), OssUtils.downloadFile(url, localFilePath);
// paramMap.get(FdfsEnum.FILE_ID.value), localFilePath); // } else if (url.contains("/group")) {
} else { // Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
File f = new File(localFilePath); // FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
URL httpurl = new URL(url); // paramMap.get(FdfsEnum.FILE_ID.value), localFilePath);
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f); } else {
} File f = new File(localFilePath);
} catch (Exception e) { URL httpurl = new URL(url);
LOGGER.error("【文件API】下载文件.[copyURLToFile]:" + e.getMessage(), e); org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); }
} } catch (Exception e) {
} LOGGER.error("【文件API】下载文件.[copyURLToFile]:" + e.getMessage(), e);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
/** }
* IOUtils工具 }
*/
public static byte[] downloadByteFromUrl(String url) throws FileException { /**
LOGGER.info("【文件API】下载文件[byte].<START>.[url]=" + url); * IOUtils工具
if (StringUtil.isEmpty(url)) { */
return null; public static byte[] downloadByteFromUrl(String url) throws FileException {
} LOGGER.info("【文件API】下载文件[byte].<START>.[url]=" + url);
byte[] data = null; if (StringUtil.isEmpty(url)) {
try { return null;
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) { }
data = OssUtils.downloadFile2Byte(url); byte[] data = null;
// } else if (url.contains("/group")) { try {
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url); if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
// data = data = OssUtils.downloadFile2Byte(url);
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value), // } else if (url.contains("/group")) {
// paramMap.get(FdfsEnum.FILE_ID.value)); // Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
} else { // data =
URL httpurl = new URL(url); // FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
data = IOUtils.toByteArray(httpurl); // paramMap.get(FdfsEnum.FILE_ID.value));
} } else {
} catch (Exception e) { URL httpurl = new URL(url);
LOGGER.error("【文件API】下载文件.[toByteArray]:" + e.getMessage(), e); data = IOUtils.toByteArray(httpurl);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); }
} } catch (Exception e) {
return data; LOGGER.error("【文件API】下载文件.[toByteArray]:" + e.getMessage(), e);
} throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
/** return data;
* InputStream }
*/
@Deprecated /**
public static InputStream downloadStreamFromUrl(String url) throws FileException { * InputStream
try { */
URL httpurl = new URL(url); @Deprecated
return httpurl.openStream(); public static InputStream downloadStreamFromUrl(String url) throws FileException {
} catch (Exception e) { try {
LOGGER.error("【文件API】下载文件.[openStream]:" + e.getMessage(), e); URL httpurl = new URL(url);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); return httpurl.openStream();
} } catch (Exception e) {
} LOGGER.error("【文件API】下载文件.[openStream]:" + e.getMessage(), e);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
/** }
* 普通情况下保存字节数据到本地文件 }
*/
public synchronized static boolean saveBytesTofile(File file, byte[] data) throws BizException { /**
FileOutputStream fos = null; * 普通情况下保存字节数据到本地文件
// 建立输出字节流 */
try { public synchronized static boolean saveBytesTofile(File file, byte[] data) throws BizException {
fos = new FileOutputStream(file); FileOutputStream fos = null;
fos.write(data); // 用FileOutputStream 的write方法写入字节数组 // 建立输出字节流
return true; try {
} catch (Exception e) { fos = new FileOutputStream(file);
e.printStackTrace(); fos.write(data); // 用FileOutputStream 的write方法写入字节数组
return false; return true;
} finally { } catch (Exception e) {
try { e.printStackTrace();
fos.close(); return false;
} catch (IOException e) { } finally {
e.printStackTrace(); try {
} fos.close();
} } catch (IOException e) {
} e.printStackTrace();
}
/** }
* 复制一个文件到另一个目录下 }
*
* @throws BizException /**
*/ * 复制一个文件到另一个目录下
public static void copyFileToFolder(File inputFile, File outputFile) throws BizException { *
FileInputStream fis = null; * @throws BizException
FileOutputStream fos = null; */
public static void copyFileToFolder(File inputFile, File outputFile) throws BizException {
try { FileInputStream fis = null;
fis = new FileInputStream(inputFile); FileOutputStream fos = null;
fos = new FileOutputStream(outputFile);
int len = 0; try {
byte[] buf = new byte[1024]; fis = new FileInputStream(inputFile);
while ((len = fis.read(buf)) != -1) { fos = new FileOutputStream(outputFile);
fos.write(buf, 0, len); int len = 0;
} byte[] buf = new byte[1024];
fis.close(); while ((len = fis.read(buf)) != -1) {
fos.close(); fos.write(buf, 0, len);
} catch (IOException ioe) { }
ioe.printStackTrace(); fis.close();
} fos.close();
} } catch (IOException ioe) {
ioe.printStackTrace();
/** }
* 合并两个文件 }
*
* @param outFile 目标文件 /**
* @param leafFile 源文件 * 合并两个文件
*/ *
public static void mergeFiles(File outFile, File leafFile) { * @param outFile
FileOutputStream fos = null; * 目标文件
FileInputStream fis = null; * @param leafFile
if (!outFile.exists()) { * 源文件
try { */
outFile.createNewFile(); public static void mergeFiles(File outFile, File leafFile) {
} catch (Exception e) { FileOutputStream fos = null;
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败"); FileInputStream fis = null;
} if (!outFile.exists()) {
} try {
try { outFile.createNewFile();
// 合并其实就是文件的续写,写成true } catch (Exception e) {
fos = new FileOutputStream(outFile, true); throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
fis = new FileInputStream(leafFile); }
int len = 0; }
for (byte[] buf = new byte[1024 * 1024]; (len = fis.read(buf)) != -1; ) { try {
fos.write(buf, 0, len); // 合并其实就是文件的续写,写成true
} fos = new FileOutputStream(outFile, true);
} catch (IOException ioe) { fis = new FileInputStream(leafFile);
ioe.printStackTrace(); int len = 0;
} finally { for (byte[] buf = new byte[1024 * 1024]; (len = fis.read(buf)) != -1;) {
try { fos.write(buf, 0, len);
if (fis != null) }
fis.close(); } catch (IOException ioe) {
if (fos != null) ioe.printStackTrace();
fos.close(); } finally {
} catch (Exception e) { try {
} if (fis != null)
} fis.close();
} if (fos != null)
fos.close();
/** } catch (Exception e) {
* 合并多个文件 }
* }
* @param outFile 输出文件, }
* @param leafFiles 文件碎片集
*/ /**
public static void mergeFileList(File outFile, List<File> leafFiles) { * 合并多个文件
FileOutputStream fos = null; *
FileInputStream fis = null; * @param outFile
if (!outFile.exists()) { * 输出文件,
try { * @param leafFiles
outFile.createNewFile(); * 文件碎片集
} catch (Exception e) { */
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败"); public static void mergeFileList(File outFile, List<File> leafFiles) {
} FileOutputStream fos = null;
} FileInputStream fis = null;
try { if (!outFile.exists()) {
// 合并其实就是文件的续写,写成true try {
fos = new FileOutputStream(outFile, true); outFile.createNewFile();
byte[] buf = new byte[1024 * 1024]; } catch (Exception e) {
for (File leafFile : leafFiles) { throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
fis = new FileInputStream(leafFile); }
int len = 0; }
while ((len = fis.read(buf)) != -1) { try {
fos.write(buf, 0, len); // 合并其实就是文件的续写,写成true
} fos = new FileOutputStream(outFile, true);
} byte[] buf = new byte[1024 * 1024];
} catch (IOException ioe) { for (File leafFile : leafFiles) {
ioe.printStackTrace(); fis = new FileInputStream(leafFile);
} finally { int len = 0;
try { while ((len = fis.read(buf)) != -1) {
if (fis != null) fos.write(buf, 0, len);
fis.close(); }
if (fos != null) }
fos.close(); } catch (IOException ioe) {
} catch (Exception e) { ioe.printStackTrace();
} } finally {
} try {
} if (fis != null)
fis.close();
/** if (fos != null)
* 音频文件转换 fos.close();
* } catch (Exception e) {
* @param data 音频byte数组 }
* @param sourExt 原始后缀 }
* @param ext 新后缀 }
* @return
* @author PENG /**
*/ * 音频文件转换
public static String audioFormatConvert(byte[] data, String sourExt, String ext) { *
File tmpdir = new File("tempdir/local"); * @param data
if (!tmpdir.exists()) { * 音频byte数组
try { * @param sourExt
tmpdir.mkdirs(); * 原始后缀
} catch (SecurityException ex) { * @param ext
System.out.println("无法创建临时文件夹"); * 新后缀
ex.printStackTrace(); * @return
} * @author PENG
} */
public static String audioFormatConvert(byte[] data, String sourExt, String ext) {
String name = UUID.randomUUID().toString(); File tmpdir = new File("tempdir/local");
File source = new File(tmpdir, name + "." + sourExt); if (!tmpdir.exists()) {
boolean creat = saveBytesTofile(source, data); try {
if (creat) { tmpdir.mkdirs();
File target = new File(tmpdir, name + "." + ext); } catch (SecurityException ex) {
AudioAttributes audio = new AudioAttributes(); System.out.println("无法创建临时文件夹");
Encoder encoder = new Encoder(); ex.printStackTrace();
audio.setCodec("libmp3lame"); }
}
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat(ext.toLowerCase()); String name = UUID.randomUUID().toString();
attrs.setAudioAttributes(audio); File source = new File(tmpdir, name + "." + sourExt);
boolean creat = saveBytesTofile(source, data);
try { if (creat) {
encoder.encode(source, target, attrs); File target = new File(tmpdir, name + "." + ext);
return target.getPath(); AudioAttributes audio = new AudioAttributes();
} catch (IllegalArgumentException e) { Encoder encoder = new Encoder();
e.printStackTrace(); audio.setCodec("libmp3lame");
return null;
} catch (InputFormatException e) { EncodingAttributes attrs = new EncodingAttributes();
e.printStackTrace(); attrs.setFormat(ext.toLowerCase());
return null; attrs.setAudioAttributes(audio);
} catch (EncoderException e) {
e.printStackTrace(); try {
return target.getPath(); encoder.encode(source, target, attrs);
} return target.getPath();
} else { } catch (IllegalArgumentException e) {
return null; e.printStackTrace();
} return null;
} } catch (InputFormatException e) {
e.printStackTrace();
/** return null;
* 获取文本的内容 } catch (EncoderException e) {
* e.printStackTrace();
* @param url return target.getPath();
* @return }
*/ } else {
public static String getTextString(String url) { return null;
LOGGER.info("【文件API】获取文本的内容.<START>.[url]=" + url); }
if (StringUtil.isEmpty(url)) { }
return null;
} /**
StringBuilder lrcString = new StringBuilder(); * 获取文本的内容
InputStream is = null; *
InputStreamReader isr = null; * @param url
try { * @return
byte[] bt = downloadByteFromUrl(url); */
is = new ByteArrayInputStream(bt); public static String getTextString(String url) {
boolean isUTF8Bom = CpdetectorEncoding.isUTF8Bom(is); LOGGER.info("【文件API】获取文本的内容.<START>.[url]=" + url);
if (isUTF8Bom) { if (StringUtil.isEmpty(url)) {
isr = new InputStreamReader(is, "UTF-8"); return null;
} else { }
Object charSet = CpdetectorEncoding.getEncoding(bt, false); StringBuilder lrcString = new StringBuilder();
if (charSet.toString().equals("UTF-8")) { InputStream is = null;
isr = new InputStreamReader(is, "UTF-8"); InputStreamReader isr = null;
} else { try {
isr = new InputStreamReader(new ByteArrayInputStream(bt), "GBK"); byte[] bt = downloadByteFromUrl(url);
} is = new ByteArrayInputStream(bt);
} boolean isUTF8Bom = CpdetectorEncoding.isUTF8Bom(is);
BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件 if (isUTF8Bom) {
String s; isr = new InputStreamReader(is, "UTF-8");
while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行 } else {
lrcString.append(System.lineSeparator() + s); Object charSet = CpdetectorEncoding.getEncoding(bt, false);
} if (charSet.toString().equals("UTF-8")) {
} catch (Exception e) { isr = new InputStreamReader(is, "UTF-8");
LOGGER.error("【文件工具】读取文件内容.<ERROR>:" + e.getMessage(), e); } else {
} finally { isr = new InputStreamReader(new ByteArrayInputStream(bt), "GBK");
try { }
if (isr != null) }
isr.close(); BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件
if (is != null) String s;
is.close(); while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
} catch (Exception e2) { lrcString.append(System.lineSeparator() + s);
} }
} } catch (Exception e) {
LOGGER.info("【文件API】获取文本的内容.<END>"); LOGGER.error("【文件工具】读取文件内容.<ERROR>:" + e.getMessage(), e);
return lrcString.toString(); } finally {
} try {
if (isr != null)
isr.close();
if (is != null)
is.close();
} catch (Exception e2) {
}
}
LOGGER.info("【文件API】获取文本的内容.<END>");
return lrcString.toString();
}
/** /**
* java 8 读取文本内容 * java 8 读取文本内容
...@@ -1004,113 +1014,114 @@ public class FileUtils { ...@@ -1004,113 +1014,114 @@ public class FileUtils {
return outFilePath; return outFilePath;
} }
/** /**
* 将文件转成base64 字符串 * 将文件转成base64 字符串
* *
* @param data * @param data
* @return * * @return *
* @throws Exception * @throws Exception
*/ */
public static String encodeBase64File(byte[] data) throws BizException { public static String encodeBase64File(byte[] data) throws BizException {
try { try {
return new String(Base64.encodeBase64(data)); return new String(Base64.encodeBase64(data));
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e); LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
return null; return null;
} }
} }
/** /**
* 将base64字符解码保存文件 * 将base64字符解码保存文件
* *
* @param base64Code * @param base64Code
* @param targetPath * @param targetPath
* @throws Exception * @throws Exception
*/ */
public static boolean decoderBase64File(String base64Code, String targetPath) throws BizException { public static boolean decoderBase64File(String base64Code, String targetPath) throws BizException {
if (base64Code == null) if (base64Code == null)
return false; return false;
OutputStream out = null; OutputStream out = null;
try { try {
// Base64解码 // Base64解码
byte[] b = Base64.decodeBase64(targetPath); byte[] b = Base64.decodeBase64(targetPath);
for (int i = 0; i < b.length; ++i) { for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据 if (b[i] < 0) {// 调整异常数据
b[i] += 256; b[i] += 256;
} }
} }
// 生成jpeg图片 // 生成jpeg图片
out = new FileOutputStream(targetPath); out = new FileOutputStream(targetPath);
out.write(b); out.write(b);
out.flush(); out.flush();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e); LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
return false; return false;
} finally { } finally {
try { try {
if (out != null) if (out != null)
out.close(); out.close();
} catch (Exception e) { } catch (Exception e) {
} }
} }
return true; return true;
} }
/** /**
* 本地文件到byte数组 * 本地文件到byte数组
* *
* @param path * @param path
* @return * @return
*/ */
public static byte[] file2byte(String path) { public static byte[] file2byte(String path) {
byte[] data = null; byte[] data = null;
FileInputStream fis = null; FileInputStream fis = null;
ByteArrayOutputStream os = null; ByteArrayOutputStream os = null;
try { try {
fis = new FileInputStream(new File(path)); fis = new FileInputStream(new File(path));
os = new ByteArrayOutputStream(); os = new ByteArrayOutputStream();
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int numBytesRead = 0; int numBytesRead = 0;
while ((numBytesRead = fis.read(buf)) != -1) { while ((numBytesRead = fis.read(buf)) != -1) {
os.write(buf, 0, numBytesRead); os.write(buf, 0, numBytesRead);
} }
data = os.toByteArray(); data = os.toByteArray();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【文件工具】文件到byte数组:" + e.getMessage(), e); LOGGER.error("【文件工具】文件到byte数组:" + e.getMessage(), e);
} finally { } finally {
try { try {
if (fis != null) if (fis != null)
fis.close(); fis.close();
if (os != null) if (os != null)
os.close(); os.close();
} catch (IOException e) { } catch (IOException e) {
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e); LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
} }
} }
return data; return data;
} }
/** /**
* 从输入流中获取数据 * 从输入流中获取数据
* *
* @param inStream 输入流 * @param inStream
* @return * 输入流
* @throws Exception * @return
*/ * @throws Exception
public static byte[] readInputStream(InputStream inStream) throws Exception { */
ByteArrayOutputStream outStream = new ByteArrayOutputStream(); public static byte[] readInputStream(InputStream inStream) throws Exception {
byte[] buffer = new byte[1024]; ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int len = 0; byte[] buffer = new byte[1024];
try { int len = 0;
while ((len = inStream.read(buffer)) != -1) { try {
outStream.write(buffer, 0, len); while ((len = inStream.read(buffer)) != -1) {
} outStream.write(buffer, 0, len);
} catch (Exception e) { }
LOGGER.error("【文件工具】文件流到byte数组:" + e.getMessage(), e); } catch (Exception e) {
} finally { LOGGER.error("【文件工具】文件流到byte数组:" + e.getMessage(), e);
inStream.close(); } finally {
} inStream.close();
return outStream.toByteArray(); }
} return outStream.toByteArray();
}
} }
...@@ -11,10 +11,11 @@ import java.math.BigDecimal; ...@@ -11,10 +11,11 @@ import java.math.BigDecimal;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.dcg.util.StringUtils;
import com.itextpdf.text.Image; import com.itextpdf.text.Image;
import com.pcloud.common.constant.AliyunConstant; import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst; import com.pcloud.common.constant.FilePathConst;
...@@ -440,6 +441,43 @@ public class ImageUtils { ...@@ -440,6 +441,43 @@ public class ImageUtils {
} }
/** /**
* 获取图片的宽度和高度(考虑了图片旋转的情况。也就是说,获得的宽就是宽,高就是高)
*
* @param img
* 图片文件
* @return
*/
public static float[] getWidthHeightSize(String fileUrl) {
Image image = null;
String localFile = null;
float[] size = new float[2];
try {
if (StringTools.contains(fileUrl, AliyunConstant.OSS_CDN_URLS)) {
localFile = OssUtils.imageAutoOrient(fileUrl, 0);
image = Image.getInstance(localFile);
} else if (fileUrl.startsWith("http")) {
image = Image.getInstance(FileUtils.downloadByteFromUrl(fileUrl));
} else {
image = Image.getInstance(fileUrl);
}
} catch (Exception e) {
LOGGER.error("【IMAGE API】获取图片的宽度和高度[getWidthHeightSize]:" + e.getMessage(), e);
} finally {
if (!StringUtil.isEmpty(localFile)) {
FileUtils.deleteFile(localFile);
}
}
if (image == null) {
size[0] = 0;
size[1] = 0;
} else {
size[0] = image.getWidth();
size[1] = image.getHeight();
}
return size;
}
/**
* 获取对比比例 * 获取对比比例
* *
* @param num1 * @param num1
...@@ -653,29 +691,30 @@ public class ImageUtils { ...@@ -653,29 +691,30 @@ public class ImageUtils {
LOGGER.error("【图片】输出文件流关闭失败:" + e.getMessage(), e); LOGGER.error("【图片】输出文件流关闭失败:" + e.getMessage(), e);
} }
} }
/** /**
* 获取图片的宽度和高度 * 获取图片的宽度和高度(未考虑图片旋转的情况。也就是说,获得的宽可能是宽也可能是高,高可能是高也肯是宽)
* *
* @param img * @param fileUrl
* 图片文件
* @return * @return
*/ */
public static float[] getWidthHeightSize(String fileUrl) { public static float[] getWidthHeightNoOrient(String fileUrl) {
Image image = null; Image image = null;
String localFile = null; String localFile = null;
float[] size = new float[2]; float[] size = new float[2];
try { try {
if (StringTools.contains(fileUrl, AliyunConstant.OSS_CDN_URLS)) { /*
localFile = OssUtils.imageAutoOrient(fileUrl, 0); * if (StringTools.contains(fileUrl, AliyunConstant.OSS_CDN_URLS)) { localFile =
image = Image.getInstance(localFile); * OssUtils.imageAutoOrient(fileUrl); image = Image.getInstance(localFile); }
} else if (fileUrl.startsWith("http")) { * else
*/
if (fileUrl.startsWith("http")) {
image = Image.getInstance(FileUtils.downloadByteFromUrl(fileUrl)); image = Image.getInstance(FileUtils.downloadByteFromUrl(fileUrl));
} else { } else {
image = Image.getInstance(fileUrl); image = Image.getInstance(fileUrl);
} }
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【IMAGE API】获取图片的宽度和高度:" + e.getMessage(), e); LOGGER.error("【IMAGE API】获取图片的宽度和高度[getWidthHeightNoOrient]:" + e.getMessage(), e);
} finally { } finally {
if (!StringUtil.isEmpty(localFile)) { if (!StringUtil.isEmpty(localFile)) {
FileUtils.deleteFile(localFile); FileUtils.deleteFile(localFile);
...@@ -692,6 +731,82 @@ public class ImageUtils { ...@@ -692,6 +731,82 @@ public class ImageUtils {
} }
/** /**
* image transcode to webp
*
* 注意:使用此方法转图片格式,机器上必须安装有谷歌cwebp工具
*
* @param fileUrl
* @return
*/
// public static UploadResultInfo transcodeToWebp(String fileUrl, int quality) {
// LOGGER.info("【IMAGE API】image transcode to webp.<START>.[fileUrl]=" + fileUrl
// + ",[quality]=" + quality);
// String fileNameAll = FileUtils.getFileNameAll(fileUrl);
// String localFilePath = FilePathConst.DOWNLOAD_PATH + fileNameAll;
// FileUtils.downloadFileFromUrl(fileUrl, localFilePath);
// String outputFilePath = FilePathConst.IMAGE_PATH + "webp/" + fileNameAll +
// ".webp";
// FileUtils.creatFiles(outputFilePath);
// UploadResultInfo uploadResultInfo = null;
// try {
// String os = System.getProperty("os.name");
// if (os.toLowerCase().startsWith("win")) {
// executeCwebp4Win(localFilePath, outputFilePath, quality);
// } else {
// executeCwebp4Linux(localFilePath, outputFilePath, quality);
// }
// uploadResultInfo = OssUtils.uploadLocalFile4Child(outputFilePath, fileUrl);
// } catch (Exception e) {
// LOGGER.error("An error happend when convert to webp. Img is: " +
// e.getMessage(), e);
// throw new FileException(FileException.FILE_CONVERT_FAIL, "transcode to webp
// is fail!");
// } finally {
// FileUtils.deleteFile(localFilePath);
// FileUtils.deleteFile(outputFilePath);
// }
// LOGGER.info("【IMAGE API】image transcode to webp.<START>.[uploadResultInfo]="
// + uploadResultInfo);
// return uploadResultInfo;
// }
/**
* execute cwebp command:cwebp [options] input_file -o output_file.webp
*
* @param inputFilePath
* @param outputFilePath
* @param quality
* @throws Exception
*/
// private static void executeCwebp4Win(String inputFilePath, String
// outputFilePath, int quality) throws Exception {
// Process process = new ProcessBuilder("cwebp", "-q", (quality == 0 ? 80 :
// quality) + "", inputFilePath, "-o",
// outputFilePath).redirectErrorStream(true).start();
// if (0 != process.waitFor()) {
// throw new Exception("process wait for fail!");
// }
// }
/**
* execute cwebp command:cwebp [options] input_file -o output_file.webp
*
* @param inputFilePath
* @param outputFilePath
* @param quality
* @throws Exception
*/
// private static void executeCwebp4Linux(String inputFilePath, String
// outputFilePath, int quality) throws Exception {
// Process process = new ProcessBuilder("/usr/local/bin/cwebp", "-q", (quality
// == 0 ? 80 : quality) + "",
// inputFilePath, "-o", outputFilePath).redirectErrorStream(true).start();
// if (0 != process.waitFor()) {
// throw new Exception("process wait for fail!");
// }
// }
/**
* 上传的图片转换成webpO * 上传的图片转换成webpO
* *
* @param localFilePath * @param localFilePath
......
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment