导入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, 宽度, 高度);
}
}