生成验证码


public
class ValidataCode extends HttpServlet { private static final long serialVersionUID = -4144854995411893258L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getValidataCode(request,response); } private final int WIDTH = 110; private final int HEIGHT = 40;//ctrl+shift+x转化大写 ctrl+shift+y转化小写 private void getValidataCode(HttpServletRequest request,HttpServletResponse response){ BufferedImage bufImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics2D graphics =bufImg.createGraphics(); graphics.setColor(new Color(250,250,210)); graphics.fillRect(0, 0, WIDTH, HEIGHT); graphics.setColor(new Color(233,150,122)); graphics.setFont(new Font("Consolas",Font.BOLD,22)); String validataStr = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"; Random random = new Random(); String validataCode=""; for(int i=0;i<4;i++){ char c = validataStr.charAt(random.nextInt(validataStr.length())); validataCode += c; int width = (i+1)*20; int radian = random.nextInt(61) - 30; graphics.rotate(radian*Math.PI/180, width, 20); graphics.drawString(c+"", width, 20); graphics.rotate(-radian*Math.PI/180, width, 20); graphics.drawLine(width, random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT)); } graphics.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT)); HttpSession session =request.getSession();//获取session session.setAttribute("VALIDATACODE", validataCode);//设置session值 try { OutputStream out = response.getOutputStream(); ImageIO.write(bufImg, "png", out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
原文地址:https://www.cnblogs.com/cpstart/p/6085328.html