天天看點

java生成随機驗證碼java生成随機驗證碼

java生成随機驗證碼

一直想自己實作一下,是以就動手做了一下,當然,也有很多不足之處,請大佬指點。

package Shuju;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Shencheng {

    public static void main(String args[]) throws IOException {
        int w = 200;
        int h = 60;
        String code = zf(5);
        BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.setColor(Color.white);
        g.fillRect(0,0,w,h);

        for(int i=100;i-->0;){
            g.setColor(new Color(rand(0,0xffffff)));
            g.drawArc(rand(0,w),rand(0,h),rand(0,w),rand(0,h),rand(0,360),rand(0,360));
        }

        Font f = new Font("黑體",Font.BOLD,30);
        g.setColor(new Color(rand(0,0xffffff)));
        g.setFont(f);
        TextLayout layout = new TextLayout(code,f,g.getFontRenderContext());
        Rectangle2D bounds = layout.getBounds();
        int x = (int)(w-bounds.getWidth())/2;
        int y =  (int)(h-bounds.getHeight())/2;;
        g.drawString(code,(int)(x-bounds.getX()),(int)(y-bounds.getY()));


        ImageIO.write(image,"png",new File("C:\\Users\\Java\\src\\驗證碼生成\\生成圖檔\\2.jpg"));
    }

    //1.随機生成驗證碼字元串
    //2.建立圖檔
    //3.背景色
    //4.添加幹擾線
    //5.繪制字元到圖檔
    //6.扭曲混淆處理
    //7.輸出

    private static String zf(int n){

        String zf = "abcdefg345678hTUVWX89YZ01234567RSTUV8TUVWX89YZ9";
        char [] ch = new char[n];
        for(int i=n;i-->0;){
            ch[i] = zf.charAt(rand(0,zf.length()));
        }
        System.out.println(ch);
        return new String(ch);
    }

    private static int rand(int a, int b){
        return (int)(Math.random()*Math.abs(a-b)+Math.min(a,b));
    }

}