導入java.awt.Color;
導入java.awt.Font;
導入java.awt.Graphics;
導入 java.awt.Graphics2D;
導入java.awt.image.BufferedImage;
導入java.io.IOException;
導入 java.util.Random;
導入 javax.imageio.ImageIO;
導入 javax.servlet.ServletException;
導入 javax.servlet.http.HttpServlet;
導入 javax.servlet.http.HttpServletRequest;
導入 javax.servlet.http.HttpServletResponse;
@SuppressWarnings(“串列”)
公共類別 validatePicture 擴充 HttpServlet {
public void doGet(HttpServletRequest 請求,HttpServletResponse 回應)
拋出 ServletException、IOException {
嘗試 {
驗證圖像(請求,回應);
} catch (異常 e) {
e.printStackTrace();
}
}
公共無效doPost(HttpServletRequest請求,HttpServletResponse回應)
拋出 ServletException、IOException {
doGet(請求,回應);
}
公共靜態最終 int WIDTH = 120;
公共靜態最終 int HEIGHT = 25;
公共無效validateimage(HttpServletRequest請求,
HttpServletResponse 回應)拋出例外狀況 {
BufferedImage bi = 新的 BufferedImage(寬度, 高度,
BufferedImage.TYPE_INT_RGB);// 在記憶體中建立一個鏡像
圖形 g = bi.getGraphics();
setBackGround(g);//設定背景色
setBorder(g);// 熟悉
drawRandomLine(g);//畫虛擬線
String random = drawRandomNum((Graphics2D) g);// 寫隨機數
request.getSession().setAttribute("隨機", 隨機);
//request.getSession(false);
響應.setContentType(“圖像/jpeg”);
// 不要設定伺服器
response.setDateHeader("expries", -1);
response.setHeader("快取控制", "無快取");
ImageIO.write(bi, "jpg", response.getOutputStream());
}
私有字串drawRandomNum(Graphics2D g){
g.setColor(Color.RED);
g.setFont(new Font("宋體", Font.BOLD, 20));
// [/u4e00-/u9fa5]中文數位區間
字串基底=“/u4e00/u4f00/u5e00/u4e50/u4e89/u4f10/u4e09”;
StringBuffer sb = new StringBuffer();
整數x = 5;
for (int i = 0; i < 4; i++) {
int 度 = new Random().nextInt() % 30;
String ch = base.charAt(new Random().nextInt(base.length())) + "";
sb.append(ch);
g.旋轉(度數 * Math.PI / 180, x, 20);
g.drawString(ch, x, 20);
g.rotate(-度 * Math.PI / 180, x, 20);
x = x + 30;
}
System.out.println(sb.toString());
返回 sb.toString();
}
私人無效drawRandomLine(圖形g){
g.setColor(Color.GREEN);
for (int i = 0; i < 3; i++) {
int x1 = new Random().nextInt(WIDTH);
int y1 = new Random().nextInt(HEIGHT);
int x2 = new Random().nextInt(WIDTH);
int y2 = new Random().nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
}
私人無效setBorder(圖形g){
g.setColor(Color.BLUE);
g.drawRect(1, 1, 寬度 - 2, 高度 - 2);
}
私人無效setBackGround(圖形g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, 寬度, 高度);
}
}