随机验证码

@Controller
public class CodeController {
    private static final long serialVersionUID = 1L;

    @ResponseBody
    @RequestMapping("/code")
    public void codeVerify(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建一个空白图片
        BufferedImage image=new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
        //获取图片画笔
        Graphics g=image.getGraphics();
        Random r=new Random();
        //设置画笔颜色
        g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        //填充矩形作为背景
        g.fillRect(0, 0, 100, 30);
        g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        String str=getNumber(7);
        g.setFont(new Font(null,Font.BOLD+Font.ITALIC,24));
        //画验证码数字
        g.drawString(str, 5, 25);
        //绘制8条干扰线
        for(int i=0;i<8;i++){
            g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
            g.drawLine(r.nextInt(100), r.nextInt(30),r.nextInt(100), r.nextInt(30));
        }
        //告诉浏览器解析成图片
        response.setContentType("image/jpeg");
        OutputStream out= response.getOutputStream();
        ImageIO.write(image, "jpeg", out);
        out.close();
    }

    public   String getNumber(int n){
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String number="";
        Random r=new Random();
        for(int i=0;i<n;i++){
            number=number+str.charAt(r.nextInt(str.length()));
        }
        return number;
    }
}

最后更新于