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
}
}
Servlet图片加水印
最新推荐文章于 2020-11-26 22:54:39 发布