import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
javax.imageio.ImageIO 가져오기;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("연속")
공개 클래스 verifyPicture는 HttpServlet을 확장합니다.
공개 무효 doGet(HttpServletRequest 요청, HttpServletResponse 응답)
ServletException, IOException이 발생합니다.
노력하다 {
verifyimage(요청, 응답);
} 잡기(예외 e) {
e.printStackTrace();
}
}
공개 무효 doPost(HttpServletRequest 요청, HttpServletResponse 응답)
ServletException, IOException이 발생합니다.
doGet(요청, 응답);
}
공개 정적 최종 int WIDTH = 120;
공개 정적 최종 int HEIGHT = 25;
공개 무효 유효성 검사 이미지(HttpServletRequest 요청,
HttpServletResponse 응답)에서 예외가 발생합니다.
BufferedImage bi = 새로운 BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);// 内存中构建一幅图象
그래픽 g = bi.getGraphics();
setBackGround(g);// 设置背景color
setBorder(g);// 设置边框
drawRandomLine(g);// 画干扰线
문자열 무작위 = drawRandomNum((Graphics2D) g);// 写随机数
request.getSession().setAttribute("random", 무작위);
//request.getSession(false);
response.setContentType("image/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;
문자열 ch = base.charAt(new Random().nextInt(base.length())) + "";
sb.append(ch);
g.rotate(정도 * 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, WIDTH - 2, HEIGHT - 2);
}
개인 무효 setBackGround(그래픽 g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, 너비, 높이);
}
}