java验证码代码_JAVA生成验证码代码

这段代码展示了如何在JAVA中生成验证码,并将其以Base64格式的图像发送到前端。首先,创建一个指定大小的BufferedImage对象,然后设置背景色、字体样式,随机生成验证码字符并绘制到图像上。接着,生成干扰线增加验证码难度。最后,将图像转换为字节数组,通过BASE64编码,并与"data:image/jpg;base64,"结合返回给前端。" 134587201,2013247,深度学习:CNN在复杂任务中的应用,"['机器学习', 'cnn', '视频处理', '音频生成']
摘要由CSDN通过智能技术生成

1 /**

2 * 生成验证码3 * 改造生成验证码的方式,将图片base64形式传到前台,而不是直接传验证码到前台4 *@return

5 *@throwsIOException6 */

7 public void imageCode() throwsIOException {8 HttpServletResponse resp =CommandContext.getResponse();9 HttpServletRequest req =CommandContext.getRequest();10 String method=req.getMethod();11 if("OPTIONS".equals(method)){12 return;13 }14 Map map=newHashMap();15

16 //在内存中创建图象

17 int width = 65, height = 38;18 BufferedImage image = newBufferedImage(width, height,19 BufferedImage.TYPE_INT_RGB);20 //获取图形上下文

21 Graphics g =image.getGraphics();22 //生成随机类

23 Random random = newRandom();24 //设定背景色

25 g.setColor(getRandColor(230, 255));26 g.fillRect(0, 0, 100, 40);27 //设定字体

28 g.setFont(new Font("Arial", Font.CENTER_BASELINE | Font.ITALIC, 20));29 //产生0条干扰线,

30 g.drawLine(0, 0, 0, 0);31

32 //存放验证码

33 StringBuffer sRand = newStringBuffer();34 for (int i = 0; i < charCount; i++) {35 String singleCode =String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);36 sRand.append(singleCode);37 //将认证码显示到图象中

38 g.setColor(getRandColor(100, 150));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成

39 g.drawString(singleCode, 14 * i + 5, 25);40 }41 for(int i=0;i

47 HttpSession session =req.getSession();48 //获取clientid

49 String clientId=SystemUtil.getClientId(req);50 if(StringUtils.isEmpty(clientId)){51 //生成clientid

52 String userAgent=req.getHeader("User-Agent");53 String sessionId=session.getId();54 String cip=IpPolicy.getClientIP(req);55 clientId=CodeUtil.genClientId(sessionId,cip,userAgent);56 }57 map.put("clientId", clientId);58 if(isValidateCodeCaseSensitive) {59 session.setAttribute("randomCode", sRand.toString());60 SystemUtil.push2Cache(clientId, sRand.toString());61 } else{62 session.setAttribute("randomCode", sRand.toString().toLowerCase());63 SystemUtil.push2Cache(clientId, sRand.toString().toLowerCase());64 }65 //图象生效

66 g.dispose();67 try{68

69 ByteArrayOutputStream outputStream = newByteArrayOutputStream();70 ImageIO.write(image, "jpg", outputStream);71 BASE64Encoder encoder = newBASE64Encoder();72 String base64Img =encoder.encode(outputStream.toByteArray());73 base64Img="data:image/jpg;base64, "+base64Img.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n;

74 map.put("verCode", base64Img);75 Object jsonObj =JSONSerializer.toJSON(map);76 byte[] json = jsonObj.toString().getBytes("UTF-8");77 resp.setContentType("text/plain;chartset=utf-8");78 resp.setHeader("Cache-Control", "no-cache");79 resp.setHeader("Expires", "0");80 resp.setIntHeader("Content-Length", json.length);81 ServletOutputStream responseOutputStream =resp.getOutputStream();82 responseOutputStream.write(json);83 //以下关闭输入流!

84 responseOutputStream.flush();85 responseOutputStream.close();86 //获得页面key值

87 return;88 } catch(IOException e) {89 logger.error("生产验证码出错",e);90 throw new SystemException("生产验证码出错",e);91 }92 }93

94

95 /**

96 * 给定范围获得随机颜色97 *98 *@paramfc99 *@parambc100 *@return

101 */

102 Color getRandColor(int fc, intbc) {103 Random random = newRandom();104 if (fc > 255)105 fc = 255;106 if (bc > 255)107 bc = 255;108 int r = fc + random.nextInt(bc -fc);109 int g = fc + random.nextInt(bc -fc);110 int b = fc + random.nextInt(bc -fc);111 return newColor(r, g, b);112 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成图片验证码可以使用 Java 的 BufferedImage 类和 Graphics 类,以下是一个简单的示例代码: ```java import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; public class ImageCode { private int width = 100; // 验证码图片的宽度 private int height = 40; // 验证码图片的高度 private int codeCount = 4; // 验证码字符个数 private int lineCount = 20; // 干扰线数量 private String code = null; // 验证码 private BufferedImage buffImg = null; // 验证码图片 private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9'}; public ImageCode() { createImageCode(); } public void createImageCode() { int x = 0, fontHeight = 0, codeY = 0; int red = 0, green = 0, blue = 0; x = width / (codeCount + 2); fontHeight = height - 5; codeY = height - 8; buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.createGraphics(); Random random = new Random(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width / 8); int ye = ys + random.nextInt(height / 8); red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); g.setColor(new Color(red, green, blue)); g.drawLine(xs, ys, xe, ye); } StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < codeCount; i++) { String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]); red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); g.setColor(new Color(red, green, blue)); g.drawString(strRand, (i + 1) * x, codeY); randomCode.append(strRand); } code = randomCode.toString(); } public BufferedImage getBuffImg() { return buffImg; } public String getCode() { return code; } } ``` 使用时可以直接调用 `ImageCode` 类的 `getBuffImg` 方法获取生成验证码图片,调用 `getCode` 方法获取验证码字符串。例如: ```java ImageCode imageCode = new ImageCode(); BufferedImage buffImg = imageCode.getBuffImg(); String code = imageCode.getCode(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值