JAVA-简单实现验证码生成

package demo;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * 验证码
 * 
 * @author Weirdo-world
 *
 */
public class Demo1 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            verificationCode(6);
        }
    }

    // 验证码生成
    public static void verificationCode(int n) {
        String str = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
        char[] ch = new char[n];
        int w = n * 20 + 10;
        int h = 40;
        Random r = new Random();
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);// 创建图像宽高
        Graphics2D g = (Graphics2D) img.getGraphics();
        g.setColor(Color.WHITE);// 颜色设置
        g.fillRect(0, 0, w, h); // 填充指定矩形
        int x = 10;
        g.setFont(new Font("微软雅黑", Font.BOLD, 15));// 字体设置
        for (int i = 0; i < n; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));// 随机颜色
            ch[i] = str.charAt(r.nextInt(str.length()));
            int y = r.nextInt(20) + 15;
            g.drawString(String.valueOf(ch[i]), x, y);
            x += 20;
        }
        // 字母数字干扰
        int nn = r.nextInt(n * 4) + 10;
        char[] chs = new char[nn];
        int xx = 10;
        for (int i = 0; i < nn; i++) {
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(100) + 10));
            chs[i] = str.charAt(r.nextInt(str.length()));
            int y = r.nextInt(20) + 10;
            g.drawString(String.valueOf(chs[i]), xx, y);
            xx += 8;
        }
        // 线条干扰
        for (int i = 0; i < nn; i++) {
            g.setStroke(new BasicStroke(r.nextInt(3)));
            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(100) + 10));
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h);
            g.drawLine(x1, y1, x2, y2);//
        }
        try {
            ImageIO.write(img, "jpg", new File("g:/image/tmp/" + new String(ch) + ".jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/Weirdo-world/p/9257912.html