700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java 生成图片验证码

java 生成图片验证码

时间:2019-03-31 02:59:18

相关推荐

java 生成图片验证码

/zh-tw/examples/detail/java-class-javax.servlet.ServletOutputStream.html

开发过程中,需要服务端返回验证码图片给前台,想想该如何实现呢?

1、字节流的输入输出

2、生成一个验证码,自定义字母数字混合实现

3、生成一个图片,可以自定义颜色设置

上代码,看结果。

/*** 生成验证码图片** @return*/public Map<String, Object> generateIdentifyCode(HttpServletRequest request, int width, int height) {Map<String, Object> map = new HashMap<>(2);String uniqueId = this.getUniqueIdFromCookie(request);if (StringUtils.isBlank(uniqueId)) {uniqueId =System.nanoTime() + RandomStringUtils.randomAlphanumeric(10);}int num = Integer.valueOf(codeLength);//生成随机码String capText = this.getIdentifyingCode(num);//redis 缓存存储,用于校验// redisClient.setex(getIdentifyingCodePreKey(uniqueId), 180, capText);map.put("image", this.img(width, height, num, capText));map.put("uniqueId", uniqueId);return map;}

/*** 获取cookie中的uniqueId** @param request* @return*/private String getUniqueIdFromCookie(HttpServletRequest request) {String uniqueId = "";Cookie[] cookies = request.getCookies();if (cookies != null) {for (Cookie cookie : cookies) {if (cookie.getName().endsWith("_UNIQUE_ID")) {uniqueId = cookie.getValue();break;}}}return uniqueId;}

/*** 生成图片** @param width* @param height* @param num* @param capText* @return*/public BufferedImage img(int width, int height, int num, String capText) {int x = width / (num + 1);int fontHeight = height - 2;int codeY = height - 4;// 定义图像bufferBufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D g = buffImg.createGraphics();// 创建一个随机数生成器类Random random = new Random();// 将图像填充为白色g.setColor(Color.WHITE);g.fillRect(0, 0, width, height);// 创建字体,字体的大小应该根据图片的高度来定Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);// 设置字体g.setFont(font);// 画边框g.setColor(Color.WHITE);g.drawRect(0, 0, width - 1, height - 1);// 随机产生160条干扰线,使图像中的认证码不易被其他程序探测到g.setColor(Color.BLACK);for (int i = 0; i < 10; i++) {int xx = random.nextInt(width);int yy = random.nextInt(height);int x1 = random.nextInt(10);int y1 = random.nextInt(12);g.drawLine(xx, yy, xx + x1, yy + y1);}// randomCode用于保存随机产生的验证码,以便用户登录后进行验证String randomCode = capText;int red = 0, green = 0, blue = 0;// 随机产生codeCount数字的验证码for (int i = 0; i < randomCode.length(); i++) {// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同red = random.nextInt(255);green = random.nextInt(255);blue = random.nextInt(255);// 用随机产生的颜色将验证码绘制到图像中g.setColor(new Color(red, green, blue));g.drawString(String.valueOf(randomCode.charAt(i)), (i + 1) * x, codeY);}return buffImg;}

/*** 生成随机码** @param num* @return*/private String getIdentifyingCode(int num) {Random random = new Random();String codeStr = "";// 生成验证码for (int i = 0; i < num; i++) {codeStr += String.valueOf(CODE_SEQUENCE[random.nextInt(36)]);}return codeStr;}

/*** 验证码长度*/@Value("5")private String codeLength;/*** 验证码字符*/private static final char[] CODE_SEQUENCE = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W','X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

controller代码:

@RequestMapping(value = "generate", method = RequestMethod.GET)public String generateIdentifyCode(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "width", required = false, defaultValue = "100") int width,@RequestParam(value = "height", required = false, defaultValue = "30") int height) {response.setDateHeader("Expires", 0);response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");response.addHeader("Cache-Control", "post-check=0, pre-check=0");response.setHeader("Pragma", "no-cache");//生成图片上的文字Map<String, Object> map = identifyingCodeService.generateIdentifyCode(request, width, height);String uniqueId = (String) map.get("uniqueId");Cookie cookie = new Cookie("_UNIQUE_ID", uniqueId);//60s过期cookie.setMaxAge(120);cookie.setPath("/");response.addCookie(cookie);ServletOutputStream out = null;try {out = response.getOutputStream();ImageIO.write((BufferedImage) map.get("image"), "jpg", out);// 强制将缓冲区所有的数据输出!out.flush();} catch (IOException e) {// ApiLogger.error("generate identify code is error, e " + e);} finally {try {if (null != out) {out.close();}} catch (IOException e) {// ApiLogger.error("generate identify code, close out is error, e " + e);}}return null;}

返回结果:

验证起来也方便,因为在创建验证码的时候已经在redis存储了value,直接请求对比验证即可。

需注意:图片生成大小调整还是得根据想要的验证码位数来调试长宽高

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。