码迷,mamicode.com
首页 > 编程语言 > 详细

使用java技术,批量进行图片水印处理

时间:2015-10-24 23:34:15      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:

步骤:

1.建立web工程[完成]
2.编写网页(含有图片)
3.编写过滤器,实现对所有请求页面的图片加水印

核心代码:

/**
* 所有请求均要经过此过滤方法
*/
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;
// 1.获取上下文路径 /WaterMark
String path = request.getContextPath();
// 2.获得请求路径 /WaterMark/images/img1.jpg
String requestUri = request.getRequestURI();
// 3.取得图片的物理路径
// 这个也可以得到工程的发布路径
// realPath+requestUri就可以得到图片的完整路径
// String realPath=request.getRealPath("/");
// 左右斜杠是不影响的
String realPath = request.getSession().getServletContext().getRealPath(
"/")
+ requestUri
.substring(requestUri.indexOf(path) + path.length());
// 4.将图片从请求中读入到字节缓冲区
FileInputStream fis = new FileInputStream(realPath);
// 创建图片缓冲区
byte[] imageBuff = new byte[fis.available()];
// 读入图片字节数据
fis.read(imageBuff);
// 5.获取图片的原始高度和宽度
Image image = new ImageIcon(imageBuff).getImage();
int imgWidth = image.getWidth(null);
int imgHeight = image.getHeight(null);
// 6.将文字信息合成到图片缓冲区
BufferedImage bufferedImage = new BufferedImage(imgWidth, imgHeight,
BufferedImage.TYPE_INT_RGB);
Graphics g = bufferedImage.createGraphics();
// 将图像数据加载进来
g.drawImage(image, 0, 0, imgWidth, imgHeight, null);
// 绘制文字
g.setColor(Color.RED); // 设置文字颜色
Font f = new Font("隶书", Font.ITALIC, 30); // 创建字体,字体风格,字号大小
g.setFont(f); // 设置字体
g.drawString("java高级工程师", 300, 900);
g.drawString("QQ:425336980", 320, 940);
g.dispose();
// 7.将缓冲区的图像转换为字节数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// 将图像缓冲区的数据编码成JPEG格式的数据
encoder.encode(bufferedImage);
// 将JPEG格式的图像转换成字节数组
byte[] resultData = out.toByteArray();
out.close();

// 8.将转化后的JPEG字节数组数据直接送到servlet响应流进行输出
res.setContentLength(resultData.length);
res.getOutputStream().write(resultData);
res.getOutputStream().close();

chain.doFilter(req, res);
}

案例下载:http://pan.baidu.com/s/1pJiTePH


使用java技术,批量进行图片水印处理

标签:

原文地址:http://www.cnblogs.com/javachenshome/p/4907816.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!