JAVA - 인증 코드 생 성 간단하게 실현

2465 단어 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();
        }
    }
}

좋은 웹페이지 즐겨찾기