Java实现验证码的小工具类
public class VerifyCodeUtil { public static void main(String[] args) throws IOException { String str = "123456789abdefghijkmnopqrstuvwxyzABCDEFHJKLMNPQRSTUVWXYZ"; String code = drawVerifyCode(new FileOutputStream("F:\\1.jpg"),str); //当用在servlet或者jsp中时,一般需要将这个方法返回的code保存到session中,用来和用户提交的验证码进行比较判断 System.out.println(code); } public static final String drawVerifyCode(OutputStream os,String str) throws IOException { if(str == null || str.trim().length() == 0){ str = "123456789abdefghijkmnopqrstuvwxyzABCDEFHJKLMNPQRSTUVWXYZ"; } int width = 120; int height = 40; // 创建一个画布 BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取一个画笔 Graphics2D g = bi.createGraphics(); // 画图过程 // 设置画笔的颜色为白色 g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); Random random = new Random(); // 画干扰线 for (int i = 0; i < 30; i++) { g.setColor(new Color(100 + random.nextInt(105),100 + random.nextInt(105), 100 + random.nextInt(105))); g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); } // 绘制黑色边框;先画干扰线,后画边框,是为了避免干扰先覆盖到边框 g.setColor(Color.BLACK); g.drawRect(0, 0, width - 1, height - 1); //设置画笔的字体 g.setFont(new Font("微软雅黑", Font.BOLD, 22)); StringBuilder sb = new StringBuilder(); // 向画布中随机输出几个字符 for (int i = 1; i < 5; i++) { // 为字 生成旋转角度 double jiaodu = random.nextInt(40) - 30; // 将旋转角度 换算弧度 double theta = jiaodu / 180 * Math.PI; g.rotate(theta, 20 * i, 0); int index = random.nextInt(str.length()); char c = str.charAt(index); sb.append(c); // 随机设置画笔颜色 g.setColor(new Color(random.nextInt(100), random.nextInt(100), random.nextInt(100))); //画出字符 g.drawString(c + "", 20 * i, 30); g.rotate(-theta, 20 * i, 0); } // 内存中资源 释放 g.dispose(); // 将画布输出到文件中 ImageIO.write(bi, "JPG", os); return sb.toString(); } }
运行生成的验证码图片效果: