+-

这几天一直在研究java添加水印的问题,也在网上找了很多的水印程序,但是对png和gif格式的图片处理的不是很理想,png和gif处理后背景都变成黑色了。困扰了很久。
找了很久终于在网上发现了个很强大的jar包:thumbnailator:Java处理图片缩放,水印的利器
该项目的google code地址为:https://code.google.com/p/thumbnailator/,可以添加水印,压缩图片,都是无损的。非常强大。有了这个工具,我就可以很轻松的对抓取过的网页图片进行处理啦!!
下面我就介绍下我的使用方法:
(1、抓取网页 -> 2、分析网页 -> 3、下载图片 -> 4、添加水印 -> 5、保存网页内存到数据库)
1、抓取网页(这个方法网上很多,jsoup或者dom4j,也有原生态的抓取的),我用的是原生态的:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * @author [email protected] */ public class GetHtmlTools { /** * 网页抓取方法 * * @param urlString 要抓取的url地址,普通方法 * @param charset 网页编码方式 * @param timeout 超时时间 * @return 抓取的网页内容 * @throws IOException 抓取异常 */ public static String GetWebContent(String urlString, final String charset, int timeout) throws IOException { if (urlString == null || urlString.length() == 0) { return null; } urlString = (urlString.startsWith("http://") || urlString.startsWith("https://")) ? urlString : ("http://" + urlString).intern(); URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn .setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");// 增加报头,模拟浏览器,防止屏蔽 conn.setRequestProperty("Accept", "text/html");// 只接受text/html类型,当然也可以接受图片,pdf,*/*任意,就是tomcat/conf/web里面定义那些 conn.setConnectTimeout(timeout); try { if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } } catch (IOException e) { e.printStackTrace(); return null; } InputStream input = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, charset)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) { sb.append(line).append("\r\n"); } if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } return sb.toString(); } }
获取内容中的img标签的src的内容,工具类:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HtmlRegexpUtil {
private final static String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签
private final static String regxpForImgTag = "<\\s*img\\s+([^>]*)\\s*>"; // 找出IMG标签
private final static String regxpForImgTagSrcAttr = "src=\"([^\"]+)\""; // 找出IMG标签的SRC属性
public static List<String> getImgSrcAttr(String inputString) throws Exception {
Pattern p_html;
Matcher m_html;
p_html = Pattern.compile(regxpForImgTagSrcAttr, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(inputString);
List<String> imgs = new ArrayList<String>();
while (m_html.find()) {
int start = m_html.start() + 5;
int end = m_html.end() - 1;
String src = inputString.substring(start, end);
imgs.add(src);
}
return imgs;
}
}
使用:List<String> imgs = HtmlRegexpUtil.getImgSrcAttr(content)
3、下载图片(工具类):
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetWebImg {
/**
* @param urlAdd (url地址,及网页中的动态链接的地址)
* @param fileName(生成文件的名称)
* @throws uploadDir(生成到服务器端指定的目录)
*/
public static void createImage(String imgurl, String filePath) throws Exception {
URL url = new URL(imgurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = conn.getInputStream(); // 通过输入流获得图片数据
byte[] getData = readInputStream(inputStream); // 获得图片的二进制数据
File imageFile = new File(filePath);
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(getData);
fos.close();
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}
使用:
for (String imgurl : imgs) {
String filePath = "c:\\abc\\test.jpg";//这里的下载后的图片,大家自己制定下
GetWebImg.createImage(imgurl, filePath);
}
4、添加水印:
ImageIcon imgIcon = new ImageIcon(filePath);
Image theImg = imgIcon.getImage();
int width = theImg.getWidth(null); int height = theImg.getHeight(null);
String watermarkPath = "c:\\abc\watermark.png";
if (width > 600 || height > 600) {
Thumbnails.of(filePath).size(600, 600).watermark(Positions.BOTTOM_RIGHT,
ImageIO.read(new File( watermarkPath)), 0.8f).toFile(filePath);
} else {
Thumbnails.of(filePath).size(width, height).watermark(Positions.BOTTOM_RIGHT,
ImageIO.read(new File(watermarkPath)), 0.8f).toFile(filePath);
}
5、保存数据到数据库,此步骤省略,大家可以根据各自的数据库结构保存。