温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中怎么生成验证码

发布时间:2021-08-07 14:17:19 来源:亿速云 阅读:97 作者:Leah 栏目:编程语言

java中怎么生成验证码,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

// package app61;import java.io.*;import java.util.*;import com.sun.image.codec.jpeg.*;import javax.servlet.*;import javax.servlet.http.*;import java.awt.*;import java.awt.image.*;public class VerifyCode extends HttpServlet {private Font mFont = new Font("Times New Roman", Font.PLAIN, 18); //设置字体public void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {//取得一个1000-9999的随机数 HttpSession session = request.getSession(true); response.setContentType("image/gif"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); int width = 60, height = 20; ServletOutputStream out = response.getOutputStream(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //设置图片大小的 Graphics gra = image.getGraphics(); Random random = new Random(); gra.setColor(getRandColor(200, 250)); //设置背景色rand垫底 gra.fillRect(0, 0, width, height); gra.setColor(Color.black); //设置字体色 gra.setFont(mFont); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 gra.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) {  int x = random.nextInt(width);  int y = random.nextInt(height);  int xl = random.nextInt(12);  int yl = random.nextInt(12);  gra.drawLine(x, y, x + xl, y + yl); } // 取随机产生的认证码(4位数字) String sRand = ""; for (int i = 0; i < 4; i++) {  String rand = String.valueOf(random.nextInt(10));  sRand += rand;  // 将认证码显示到图象中  gra.setColor(new Color(20 + random.nextInt(110),  20 + random.nextInt(110),  20 + random.nextInt(110))); //调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成  gra.drawString(rand, 13 * i + 6, 16); } session.setAttribute("rand",sRand); // session.setAttribute("getImg", sRand); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); out.close();}static Color getRandColor(int fc, int bc) { //给定范围获得随机颜色 Random random = new Random(); if (fc > 255)  fc = 255; if (bc > 255)  bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b);} //Clean up resources public void destroy() {  }}

关于java中怎么生成验证码问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI