验证码
public class CodeImg extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int width = 110;
int height = 25;
// 在内存中创建一个图片
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 创建画笔
Graphics g = img.getGraphics();
// 添加背景色
g.setColor(Color.PINK);
g.fillRect(1, 1, width - 2, height - 2);
// 添加字样
Random rm = new Random();
g.setColor(Color.BLUE);
g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 18));
int position = 20;
for (int i = 0; i < 4; i++) {
g.drawString(rm.nextInt(10) + "", position, 20);
position += 20;
}
// 加入干扰线
g.setColor(Color.BLACK);
for (int i = 0; i < 9; i++) {
g.drawLine(rm.nextInt(width), rm.nextInt(height), rm.nextInt(width), rm.nextInt(height));
}
// 以流的方式响应给客户端
ImageIO.write(img, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
网友评论