Servlet图片加水印

来源:互联网 发布:下载billboard软件 编辑:程序博客网 时间:2024/06/05 03:11
package cn.cnvc.servlet;import java.awt.Color;import java.awt.Graphics;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.io.OutputStream;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ImageServlet extends HttpServlet {/** *  */private static final long serialVersionUID = 1L;/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doPost(request, response);}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */@SuppressWarnings("deprecation")public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//获取服务器路径和请求资源String dir=request.getRealPath("/");String resource=request.getRequestURI();resource=resource.substring(request.getContextPath().length()+1);String path=dir+resource;File file=new File(path);System.out.println(path);if(!file.exists()){response.setStatus(404);response.flushBuffer();return;}Image src=ImageIO.read(file); int wideth = src.getWidth(null); int height = src.getHeight(null); BufferedImage image = new BufferedImage(wideth, height,BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); g.drawImage(src, 0, 0, wideth, height, null); g.setColor(Color.white); g.drawString("cnvc.com.cn", 10, 10); g.dispose(); HttpServletResponse hResponse=(HttpServletResponse)response; OutputStream output=hResponse.getOutputStream(); response.setContentType("image/jpeg"); response.setHeader("Pragma","no-cache"); response.setHeader("Cache-Control","no-cache"); response.setIntHeader("Expires",-1); ImageIO.write(image,"JPEG", output);}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}

0 1
原创粉丝点击