水印开发是web开发中一种比较常见的功能,实现的代码很简单。下面举例实现图片的水印效果,通过jsp页面请求servlet服务响应,把响应的结果反映给客户端。
水印功能代码如下:
1、jsp页面:
public class BasedServlet extends HttpServlet {
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
Class<? extends BasedServlet> reqClass=this.getClass();
req.setCharacterEncoding("utf-8");
res.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
String op=req.getParameter("op");
try {
Method method=reqClass.getMethod(op, HttpServletRequest.class,HttpServletResponse.class);
Object invoke=method.invoke(this,req,res);
if(invoke!=null){
req.getRequestDispatcher((String)invoke).forward(req, res);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4、servlet服务类:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;
import com.ls.util.BasedServlet;
public class ImgServlet extends BasedServlet {
public void updateImg(HttpServletRequest req,HttpServletResponse res){
//获取图片
String mainImg=req.getServletContext().getRealPath("/upfile/Koala.jpg");
String logoImg=req.getServletContext().getRealPath("/upfile/logo.JPG");
//转换图片
ImageIcon mainIcon=new ImageIcon(mainImg);
ImageIcon logoIcon=new ImageIcon(logoImg);
//创建画布
BufferedImage buffImg= new BufferedImage(mainIcon.getIconWidth(), mainIcon.getIconHeight(),BufferedImage.TYPE_3BYTE_BGR);
//获得画笔
Graphics gt=buffImg.getGraphics();
//绘制图片
gt.drawImage(mainIcon.getImage(),0,0,null);
gt.drawImage(logoIcon.getImage(),17,400,null);
//将绘制的图给主图
gt.setColor(Color.pink);
gt.setFont(new Font(“黑体”, Font.BOLD, 24));
gt.drawString(“水印”,200, 200);
//存放画好的图
String saveImg=req.getServletContext().getRealPath("/upfile");
try {
ImageIO.write(buffImg,“jpg”, new File(saveImg+"/mainsimg5.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}