java生成CAPTCHA验证码并逐步优化

纯Java实现CAPTCHA验证码,验证码被机器破解由易到难。

图片如下:

 eazy:     

normal: 

hard:      

very hard:    

1.指明验证码的宽和高,以及画板和画笔

// 验证码图片的宽度。
		int width = 70;
		// 验证码图片的高度。
		int height = 30;
		
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		Graphics g=image.getGraphics();		
		// 随机操作對象
	    Random random=new Random();

2.生成随机字符串(验证码)

String s ="";
         for(int i=0;i<4;i++){
        	 s=getRandomCode(0, 4, null);
             System.out.println(s);
         }



	/**
	 * 生成随机字符串
	 * @param type 类型  0:大小写+数字  1:大小写  2:数字
	 * @param length 长度
	 * @param exChars 排除的字符
	 * @return
	 */
	public static String getRandomCode(int type,int length,String exChars){
		StringBuffer sb=new StringBuffer();
		Random random=new Random();
		int i=0;
		switch (type) {
		case 0:
			while(i<length){
                int t=random.nextInt(123);
                if((t>=97||(t>=65&&t<=90)||(t>=48&&t<=57))&&(exChars==null||exChars.indexOf((char)t)<0)){
                    sb.append((char)t);
                    i++;
                }
            }
			break;
		case 1:
			while(i<length){
                int t=random.nextInt(123);
                if((t>=97||(t>=65&&t<=90))&&(exChars==null||exChars.indexOf((char)t)<0)){
                    sb.append((char)t);
                    i++;
                }
            }
			break;
		case 2:
			while(i<length){
                int t=random.nextInt(123);
                if(((t>=48&&t<=57))&&(exChars==null||exChars.indexOf((char)t)<0)){
                    sb.append((char)t);
                    i++;
                }
            }
			break;
		default:
			break;
		}	
		return sb.toString();
		
	}

3.设置背景颜色、字体以及边框

// 设定图像背景色(因为是做背景,所以偏淡)
         Color color=getRandomColor(200, 250);
 		g.setColor(color);
 		g.fillRect(0, 0, width, height);
 		
 		// 创建字体,字体的大小应该根据图片的高度来定。
		Font font = new Font("Times New Roman", Font.HANGING_BASELINE, 28);
		// 设置字体。
		g.setFont(font);
		
            // 画边框。
	    g.setColor(Color.BLACK);
	    g.drawRect(0, 0, width - 1, height - 1);

4.随机生成多条干扰线,加大攻击难度。

// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到。
		g.setColor(getRandomColor(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);
			g.drawLine(x, y, x + xl, y + yl);
		}	

其中getRandomColor():

// 给定范围获得随机颜色
	public static Color getRandomColor(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);
		}

5.按位写入验证码,分顺序分布和随机分布。

// 写入验证码。
		for (int i = 0; i < s.length(); i++) {	
			String strRand = s.charAt(i)+"";
			// 生成随机颜色
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));

			//等间隔出现 
			//g.drawString(strRand, 15*i + 6 , 24);
			
			//随机位置出现
			g.drawString(strRand, (int) (15*i+Math.random()*10) , (int) (Math.random()*10+20));
			

			
		}

6.再进行扭曲图片。

//扭曲图片
		shearX(g, width, height, color);
        shearY(g, width, height, color);
//延水平方向扭曲图片
	private static void shearX(Graphics g, int w1, int h1, Color color) {
	     Random random=new Random();
	     int period = 2;
	
	     boolean borderGap = true;
	     int frames = 1;
         int phase = random.nextInt(2);
  
         for (int i = 0; i < h1; i++) {
             double d = (double) (period >> 1)* Math.sin((double) i / (double) period 
            		 + (2.2831853071795862D * (double) phase)/ (double) frames);
             g.copyArea(0, i, w1, 1, (int) d, 0);
             if (borderGap) {
                 g.setColor(color);
                 g.drawLine((int) d, i, 0, i);
                 g.drawLine((int) d + w1, i, w1, i);
             }
         }
		  
     }
	
	//延垂直方向扭曲图片
	private static void shearY(Graphics g, int w1, int h1, Color color) {
        Random random=new Random();
        int period = random.nextInt(5) + 10; // 35;
 
        boolean borderGap = true;
        int frames = 20;
        int phase = random.nextInt(2);
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                            + (2.2831853071795862D * (double) phase)/ (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }
 
        }
 
    }

6.图像生效,并以文件形式输出。

// 图象生效
		g.dispose();
		output(image);
        

其中 output(image) 输出jpg文件 :

//将图片输出成文件
	public static void output(BufferedImage image) {
		//String randomCode = getRandomCode(0, 4, null);
		try {
			File file = new File("d:/test_captcha.jpg");
			ImageIO.write(image, "jpg", file);
		} catch (IOException e) {
			// TODO: handle exception
			System.out.println("保存失敗");
			e.printStackTrace();
		}
		
	}

文章多处参考自:https://www.cnblogs.com/maixiaodou/p/7305729.html









  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生成图形验证码可以使用 Java 的 BufferedImage 类和 Java 的 Graphics2D 类,具体步骤如下: 1. 创建 BufferedImage 对象,指定宽度、高度和图片类型(例如 BufferedImage.TYPE_INT_RGB)。 2. 获取 Graphics2D 对象,使用 BufferedImage 的 createGraphics() 方法。 3. 设置验证码图片的背景色和字体颜色。 4. 生成随机字符串,并在图片上绘制字符串。 5. 在图片上绘制干扰线、干扰点等。 6. 将 BufferedImage 对象输出为图片文件或输出流。 以下是一个简单的示例代码: ``` import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random; public class CaptchaGenerator { private static final int WIDTH = 120; private static final int HEIGHT = 40; private static final int FONT_SIZE = 20; private static final int LINE_COUNT = 10; private static final int POINT_COUNT = 100; public static BufferedImage generateCaptcha() { // 创建 BufferedImage 对象 BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); // 获取 Graphics2D 对象 Graphics2D g2d = image.createGraphics(); // 设置背景色和字体颜色 g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, WIDTH, HEIGHT); g2d.setColor(Color.BLACK); g2d.setFont(new Font("Arial", Font.BOLD, FONT_SIZE)); // 生成随机字符串,并在图片上绘制字符串 String captcha = generateRandomString(); for (int i = 0; i < captcha.length(); i++) { g2d.drawString(String.valueOf(captcha.charAt(i)), 10 + FONT_SIZE * i, HEIGHT / 2 + FONT_SIZE / 2); } // 在图片上绘制干扰线、干扰点等 Random random = new Random(); for (int i = 0; i < LINE_COUNT; i++) { g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); g2d.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT), random.nextInt(WIDTH), random.nextInt(HEIGHT)); } for (int i = 0; i < POINT_COUNT; i++) { g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256))); g2d.fillRect(random.nextInt(WIDTH), random.nextInt(HEIGHT), 1, 1); } // 释放 Graphics2D 对象 g2d.dispose(); return image; } private static String generateRandomString() { String source = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { sb.append(source.charAt(random.nextInt(source.length()))); } return sb.toString(); } } ``` 使用时,可以将生成的 BufferedImage 对象输出为图片文件或输出流,例如: ``` BufferedImage captchaImage = CaptchaGenerator.generateCaptcha(); ImageIO.write(captchaImage, "JPEG", new File("captcha.jpg")); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值