public class HtmlImgUtil {
/**
* 将html中的图片下载到服务器,并且使用服务器上图片的地址替换图片的网络路径
*
* @param html 要处理的html
* @param uploadFolder 服务器上保存图片的目录
* @return
*/
public static String transHtml(String html, String uploadFolder, OssService ossService,String findUrl) {
List<String> imgList = getImgStrList(html,findUrl);
if (imgList != null && imgList.size()>0){
for (String imgStr : imgList) {
try {
String newUrl = downloadUrlAndUploadOss(imgStr, UUID.randomUUID() + ".png", uploadFolder,ossService);
html = html.replace(imgStr, newUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return html;
}
/**
* 图片复制下载
*
* @param imageUrl 图片路径
* @param fileName 文件名
* @param pathName 路径名
* @return
* @throws Exception
*/
public static String downloadUrlAndUploadOss(String imageUrl, String fileName, String pathName,OssService ossService) throws Exception {
String ossUrl = "";
//下载的图片路径
String path = "";
if (imageUrl.contains("wx_fmt=gif")) {
//动图下载
path = System.currentTimeMillis() + ".gif";
getGif(imageUrl, path);
} else {
//图片下载
BufferedImage image = ImageIO.read(new URL(imageUrl));
path = ImageWordsUtil.saveImage(image, "", fileName, "png");
}
//上传至oss
File articleFile = new File(path);
MultipartFile multipartFile = ImageWordsUtil.fileToMultipartFile(articleFile, "");
//自己osss上传的方法
ossUrl = ossService.uploadFileGetUrl(pathName, multipartFile);
//删除临时文件
articleFile.delete();
return ossUrl;
}
/**
* 获取动态图转换
* @param urls 原动态图url路径
* @param path 复制后
*/
public static void getGif(String urls, String path) {
try {
URL url = new URL(urls);
java.io.BufferedInputStream bis = new BufferedInputStream(url
.openStream());
byte[] bytes = new byte[1024];
OutputStream bos = new FileOutputStream(new File(
path));
int len;
while ((len = bis.read(bytes)) > 0) {
bos.write(bytes, 0, len);
}
bis.close();
bos.flush();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 提取HTML字符串中的img
*
* @param htmlStr 要处理的html字符串
* @return
*/
public static List<String> getImgStrList(String htmlStr,String findUrl) {
List<String> list = new ArrayList<>();
String img = "";
Pattern p_image;
Matcher m_image;
String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
m_image = p_image.matcher(htmlStr);
while (m_image.find()) {
img = m_image.group();
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
while (m.find()) {
String path = m.group(1);
//检查图片路径是否为本服务器oss路径
boolean status = path.contains(findUrl);
// boolean status = path.contains("路径");
if (status) {
System.out.println("包含");
} else {
list.add(handleSrc(path));
}
}
}
return list;
}
/**
* 去除src路径中的前后引号
*
* @param src 图片的src路径
* @return
*/
private static String handleSrc(String src) {
if (src != null) {
if (src.startsWith("'") || src.startsWith("\"")) {
return src.substring(1, src.length());
}
if (src.endsWith("'") || src.endsWith("\"")) {
return src.substring(0, src.length());
}
}
return src;
}
/**
* @param savedImg
* 待保存的图像
* @param saveDir
* 保存的目录
* @param fileName
* 保存的文件名,必须带后缀,比如 "beauty.jpg"
* @param format
* 文件格式:jpg、png或者bmp
* @return
*/
public static String saveImage(BufferedImage savedImg, String saveDir,String fileName, String format) {
boolean flag = false;
// 先检查保存的图片格式是否正确
String[] legalFormats = { "jpg", "JPG", "png", "PNG", "bmp", "BMP" };
int i = 0;
for (i = 0; i < legalFormats.length; i++) {
if (format.equals(legalFormats[i])) {
break;
}
}
if (i == legalFormats.length) { // 图片格式不支持
System.out.println("不是保存所支持的图片格式!");
// return false;
return null;
}
// 再检查文件后缀和保存的格式是否一致
String postfix = fileName.substring(fileName.lastIndexOf('.') + 1);
if (!postfix.equalsIgnoreCase(format)) {
System.out.println("待保存文件后缀和保存的格式不一致!");
// return false;
return null;
}
String fileUrl = saveDir + fileName;
File file = new File(fileUrl);
try {
flag = ImageIO.write(savedImg, format, file);
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}
public static MultipartFile fileToMultipartFile(File file, String fieldName) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
MultipartFile mfile = new CommonsMultipartFile(item);
return mfile;
}
}