生成验证码图片
来源:互联网 发布:还原备份软件 编辑:程序博客网 时间:2024/06/07 02:50
前端页面
//第一次通过img里面的src去访问后台的写验证码图片的方法,通过onclick来实现每次点击图片刷新验证码
<img src="/account/getCodeImg" onclick="this.src = '/account/getCodeImg' + '?v=' + Math.random()" style="display: block;float: left;height:34px;margin-left:10px;" />
后台
//每次后台生成验证码图片后存到session里面,登录的时候获取出来验证
/** * 图片验证码 * * @throws IOException */@RequestMapping("/getCodeImg")public void getCodeImg(HttpServletRequest request, HttpServletResponse response) throws IOException {// 设置不缓存图片response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "No-cache");response.setDateHeader("Expires", 0);// 指定生成的响应图片,一定不能缺少这句话,否则错误.response.setContentType("image/jpeg");int width = 100, height = 40; // 指定生成验证码的宽度和高度BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 创建BufferedImage对象,其作用相当于一图片Graphics g = image.getGraphics(); // 创建Graphics对象,其作用相当于画笔Graphics2D g2d = (Graphics2D) g; // 创建Grapchics2D对象Random random = new Random();Font mfont = new Font("宋体", Font.BOLD, 20); // 定义字体样式g.setColor(getRandColor(200, 250));g.fillRect(0, 0, width, height); // 绘制背景g.setFont(mfont); // 设置字体g.setColor(getRandColor(180, 200));// 绘制100条颜色和位置全部为随机产生的线条,该线条为2ffor (int i = 0; i < 40; i++) {int x = random.nextInt(width - 1);int y = random.nextInt(height - 1);int x1 = random.nextInt(6) + 1;int y1 = random.nextInt(12) + 1;BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); // 定制线条样式Line2D line = new Line2D.Double(x, y, x + x1, y + y1);g2d.setStroke(bs);g2d.draw(line); // 绘制直线}// 输出由英文,数字,和中文随机组成的验证文字,具体的组合方式根据生成随机数确定。String sRand = "";String ctmp = "";int itmp = 0;// 制定输出的验证码为四位for (int i = 0; i < 4; i++) {itmp = random.nextInt(10) + 48;ctmp = String.valueOf((char) itmp);sRand += ctmp;Color color = new Color(20 + random.nextInt(110), 20 + random.nextInt(110), random.nextInt(110));g.setColor(color);// 将生成的随机数进行随机缩放并旋转制定角度 PS.建议不要对文字进行缩放与旋转,因为这样图片可能不正常显示/* 将文字旋转制定角度 */// Graphics2D g2d_word = (Graphics2D) g;// AffineTransform trans = new AffineTransform();// trans.rotate((45) * 3.14 / 180, 15 * i + 8, 7);// /* 缩放文字 */// float scaleSize = random.nextFloat() + 0.8f;// if (scaleSize > 1f)// scaleSize = 1f;// trans.scale(scaleSize, scaleSize);// g2d_word.setTransform(trans);g.drawString(ctmp, 15 * i + 20, 30);}HttpSession session = request.getSession(true);session.setAttribute("randCheckCode", sRand);g.dispose(); // 释放g所占用的系统资源ImageIO.write(image, "JPEG", response.getOutputStream()); // 输出图片}/* 该方法主要作用是获得随机生成的颜色 */private Color getRandColor(int s, int e) {Random random = new Random();if (s > 255)s = 255;if (e > 255)e = 255;int r, g, b;r = s + random.nextInt(e - s); // 随机生成RGB颜色中的r值g = s + random.nextInt(e - s); // 随机生成RGB颜色中的g值b = s + random.nextInt(e - s); // 随机生成RGB颜色中的b值return new Color(r, g, b);}
阅读全文