java生成随机验证码

java生成随机验证码

用到的主要类:
Random 生成随机数
BufferedImage 图片缓冲区
Graphics2D 画笔
ImagerIO(RenderedImage image,String formatName,outputStream os)
Color      new Color(int r,int g,int b)
Font      new Font(String name, int style, int size) 根据指定名称、样式和磅值大小,创建一个新 Font。

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

import javax.imageio.ImageIO;
/*
 * 生成随机验证码
 */
public class VerifiCode {
    private int width = 60;   //图片宽度
    private int height = 25;    //图片高度
    private Random rm = new Random();
    private String text;        //验证码文本
    private String codes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";//验证码
    private String[] fontNames = {"宋体","华文楷体", "黑体", "微软雅黑", "楷体_GB2312"}; //字体名称
    /*
     *获取随机字体 
     */
    public Font randomFont(){
        int style = rm.nextInt(4);  //字体样式:0是无样式,1是加粗,2是斜体,3是加粗加斜体
        int size = rm.nextInt(4)+20;    //字体大小
        int index = rm.nextInt(fontNames.length);
        String fontName = fontNames[index]; 
        Font font = new Font(fontName,style,size);
        return font;
    }
    /*
     * 获取随机颜色
     */
    public Color randomColor(){
        int r = rm.nextInt(150);
        int g = rm.nextInt(150);
        int b = rm.nextInt(150);
        Color color = new Color(r,g,b);
        return color;
    }
    /*
     *对验证码图片画干扰线,防止暴力破解 
     */
    public BufferedImage drawLine(BufferedImage image){
        Graphics2D g = image.createGraphics();
        for(int i=0;i<3;i++){               //三条干扰线
            int x1 = rm.nextInt(width);
            int y1 = rm.nextInt(height);
            int x2 = rm.nextInt(width);
            int y2 = rm.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }
        return image;
    }
    /*
     *生成验证码图片 
     */
    public BufferedImage drawImage(){
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int index = rm.nextInt(codes.length());
            String s= codes.charAt(index)+"";
            sb.append(s);
            float x = 1.0f*width/5*(i+1);
            g.setFont(randomFont());
            g.setColor(randomColor());
            g.drawString(s,x,height-5);
        }
        this.text = sb.toString();
        drawLine(image);
        return image;
    }

    public String getText() {
        return text;
    } 

    public static void input(BufferedImage image,OutputStream os) throws IOException{
        ImageIO.write(image,"JPEG",os);     //将获取的image写入到输出流os中
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值