java生成验证码
2016-12-29 16:02
435 查看
前端调用:
<img src="${CTX }/captcha" >
后台代码:
<img src="${CTX }/captcha" >
后台代码:
private int w = 70; private int h = 26; /** * 生成验证码 */ @RequestMapping public void captcha(String width, String height, HttpServletResponse response, Model model) { OutputStream out = null; try { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) { w = NumberUtils.toInt(width); h = NumberUtils.toInt(height); } BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setColor(getRandColor(220, 250));// 生成背景 g.fillRect(0, 0, w, h); for (int i = 0; i < 8; i++) // 加入干扰线条 { g.setColor(getRandColor(40, 150)); Random random = new Random(); int x = random.nextInt(w); int y = random.nextInt(h); int x1 = random.nextInt(w); int y1 = random.nextInt(h); g.drawLine(x, y, x1, y1); } String s = createCharacter(g);// 生成字符 SessionUtils.put(Constants.SESSION_KEY_CAPTCHA, s); g.dispose(); out = response.getOutputStream(); ImageIO.write(image, "JPEG", out); out.close(); } catch (Exception e) { logger.error("Write Captcha Error", e); } finally { IOUtils.closeQuietly(out); } } private Color getRandColor(int fc, int bc) { int f = fc; int b = bc; Random random = new Random(); if (f > 255) { f = 255; } if (b > 255) { b = 255; } return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f)); } private String createCharacter(Graphics g) { char[] codeSeq = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' }; //字体:宋体, 新宋体, 黑体, 楷体, 隶书 String[] fontTypes = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" }; Random random = new Random(); StringBuilder s = new StringBuilder(); for (int i = 0; i < 4; i++) { String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]); g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100))); g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)], Font.BOLD, 26)); g.drawString(r, 15 * i + 5, 19 + random.nextInt(8)); s.append(r); } return s.toString(); }
相关文章推荐
- java生成验证码【原创】
- java随机验证码的生成
- java生成验证码
- 生成图片验证码的时候抛出:java.lang.illegalStateException
- 使用jsp生成验证码使用简单在java或jsp页面调用简单
- Java实现图形验证码的生成部分
- java生成验证码图片—servlet篇(第一种)
- Java随机生成动态验证码
- JAVA生成彩色验证码
- Java生成验证码图片的程序
- Java生成彩色验证码
- Java 生成随机验证码
- java生成彩色随即验证码
- Java生成验证码图片的程序
- java随机生成动态验证码
- java生成数字验证码
- java 生成MD5验证码
- 用java代码 生成验证码的一个示例类
- Java生成验证码图片的程序
- Java生成验证码图片的程序