import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
/**
* @author
*/
public class ImageUtil {
private static final Logger logger = Logger.getLogger(ImageUtil.class);
// 图片压缩宽度
private static final Integer ratio = 480;
public static List<String> getImgUrl(String content) {
String imgEx_script = "<img.*src\\s*=\\s*(.*?)[^>]*?>"; // 定义img的正则表达式
Pattern p_script = Pattern.compile(imgEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(content);
List<String> list = new ArrayList<String>();
while (m_script.find()) {
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(m_script.group());
while (m.find()) {
list.add(m.group(1));
}
}
/*
* if (m_script.find()) { Matcher m =
* Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)"
* ).matcher(m_script.group(0)); if (m.find()) { list.add(m.group(1)); }
* }
*/
return list;
}
public static String repalceImgUrl(String content, String dir, String accessToken) throws Exception {
Document doc = Jsoup.parse(content);
Elements pngs = doc.select("img[src]");
for (Element element : pngs) {
String imgUrl = element.attr("src");
File imageFile = getUrlFile(imgUrl, dir);
WeiXinVo vo = WeiXinUtil.uploadImg(accessToken, imageFile);
if (vo.getUrl() != null) {
element.attr("src", vo.getUrl());
}
}
return doc.toString();
}
public static String repalceAllImg(String content) {
Document doc = Jsoup.parse(content);
Elements pngs = doc.select("img[src]");
for (Element element : pngs) {
String imgUrl = element.attr("src");
imgUrl = imgUrl.replace("http:/xxx", "http://bbb");
element.attr("src", imgUrl);
}
return doc.toString();
}
public static String getImgUrl_first(String content) {
String imgEx_script = "<img.*src\\s*=\\s*(.*?)[^>]*?>"; // 定义img的正则表达式
Pattern p_script = Pattern.compile(imgEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(content);
String result = null;
if (m_script.find()) {
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(m_script.group(0));
if (m.find()) {
result = m.group(1);
}
}
return result;
}
private static String downloadFromUrl(String url, String dir) {
String fileName = null;
try {
// -------------------------------------
// System.setProperty("http.proxySet", "true");
// System.setProperty("http.proxyHost", "proxy2.xxx.com.cn");
// System.setProperty("http.proxyPort", "80");
// ---------------------------------------
URL httpurl = new URL(url);
fileName = getFileNameFromUrl(url);
File file = new File(dir + File.separator + fileName);
File fileDir = new File(dir);
FileUtils.forceMkdir(fileDir);
FileUtils.copyURLToFile(httpurl, file);
} catch (Exception e) {
logger.error("downloadFromUrl", e);
}
return fileName;
}
private static String getFileNameFromUrl(String url) {
String name = new Long(System.currentTimeMillis()).toString() + ".X";
int index = url.lastIndexOf("/");
if (index > 0) {
name = url.substring(index + 1);
if (name.trim().length() > 0) {
return name.replace("=", ".");
}
}
return name;
}
public static File getUrlFile(String url, String dir) {
File file = null;
if (url.startsWith("http://")) {
String fileName = downloadFromUrl(url, dir);
file = new File(dir + File.separator + fileName);
} else {
String fileName = getFileNameFromUrl(url);
file = new File(dir + File.separator + fileName);
}
return file;
}
private static File getReduceFile(File imgFile) throws IOException {
String filename = imgFile.getName();
String name = filename.substring(0, filename.lastIndexOf("."));
String extensionName = StringUtils.substring(filename, StringUtils.lastIndexOf(filename, "."));
File reduceFile = new File(imgFile.getParent(), name + "_" + extensionName);
FileUtils.copyFile(imgFile, reduceFile);
return reduceFile;
}
/**
* 图片自动压缩
*
* @param imgFile
* @return
*/
public static Icon imageReduce(File imgFile) {
// 在缓存中构造Image对象
Icon ret = null;
double high = 0.0;
double scale = 0.0;
try {
File reduceFile = getReduceFile(imgFile);
// 把图像数据获取到存在BufferedImage里边
BufferedImage bi = ImageIO.read(reduceFile);
if (!reduceFile.exists()) {
reduceFile.mkdirs();
}
// 宽度超过比例压缩
if (bi.getWidth() > ratio) {
// 想要的宽度/图片的宽度,得出比例
scale = ratio.doubleValue() / bi.getWidth();
// 比例*高度为等比的高度
high = bi.getHeight() * scale;
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(scale, scale), null);
Image item = bi.getScaledInstance((int) ratio, (int) high, BufferedImage.SCALE_DEFAULT);
item = op.filter(bi, null);
ImageIO.write((BufferedImage) item, "gif", reduceFile);
ret = new ImageIcon(reduceFile.getPath());
} else {
ret = new ImageIcon(reduceFile.getPath());
}
} catch (Exception e1) {
logger.error("图片压缩异常", e1);
}
return ret;
}
public static String imageReduceUrl(String uploadDir, String url) {
String result = null;
// 在缓存中构造Image对象
Icon ret = null;
double high = 0.0;
double scale = 0.0;
try {
// ----本地环境需要设置代理----
// System.setProperty("proxySet", "true");
// System.setProperty("proxyHost", "proxy2.xxx.com.cn");
// System.setProperty("proxyPort", "80");
// ----------------------
URL sUrl = new URL(url);
String fileName = getFileNameFromUrl(url);
File imgFile = new File(uploadDir, fileName);
if (!imgFile.exists()) {
FileUtils.copyURLToFile(sUrl, imgFile);
}
File reduceFile = getReduceFile(imgFile);
// 把图像数据获取到存在BufferedImage里边
BufferedImage bi = ImageIO.read(sUrl);
// 宽度超过比例压缩
if (bi.getWidth() > ratio) {
// 想要的宽度/图片的宽度,得出比例
scale = ratio.doubleValue() / bi.getWidth();
// 比例*高度为等比的高度
high = bi.getHeight() * scale;
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(scale, scale), null);
Image item = bi.getScaledInstance((int) ratio, (int) high, BufferedImage.SCALE_DEFAULT);
item = op.filter(bi, null);
ImageIO.write((BufferedImage) item, "gif", reduceFile);
ret = new ImageIcon(reduceFile.getPath());
} else {
ret = new ImageIcon(reduceFile.getPath());
}
result = reduceFile.getName();
} catch (Exception e1) {
logger.error("图片压缩异常", e1);
}
return result;
}
/**
* 获取图片宽度
*
* @return
*/
public static int getImageWidth(String url, File file) {
int result = 0;
try {
BufferedImage img = ImageIO.read(file);
result = img.getWidth();
} catch (Exception e) {
logger.error("获取图片宽度异常", e);
}
return result;
}
/**
* 正文添加封面图片
*
* @param imgUrl
* @param content
* @return
*/
public static String addCoverImg(String imgUrl, String content) {
if (StringUtils.isNotEmpty(content) && content.startsWith("<img")) {
Document doc = Jsoup.parse(content);
Elements pngs = doc.select("img");
if (pngs != null && !pngs.isEmpty()) {
if (imgUrl.equals(pngs.first().attr("src"))) {
content = content.replaceFirst(pngs.first().toString(), "");
content = content.replaceFirst("<br />", "");
content = content.replaceFirst("<br />", "");
}
}
}
return "<img src=\"" + imgUrl + "\" /><br />" + content;
}
/**
* 正文移除封面图片
*
* @param imgUrl
* @param content
* @return
*/
public static String removeCoverImg(String imgUrl, String content) {
if (StringUtils.isNotEmpty(content) && content.startsWith("<img")) {
Document doc = Jsoup.parse(content);
Elements pngs = doc.select("img");
if (pngs != null && !pngs.isEmpty()) {
if (imgUrl.equals(pngs.first().attr("src"))) {
content = content.replaceFirst(pngs.first().toString(), "");
content = content.replaceFirst("<br />", "");
content = content.replaceFirst("<br />", "");
}
}
}
return content;
}
public static void main(String[] args) throws Exception {
// downloadFromUrl("http://url",
// "d:/");
// imageReduceUrl("d:/pic/",
// "http://url/banner1.jpg");
File file = new File(
"D://Koala.jpg");
// getReduceFile(file);
imageReduce(file);
}
}