随机验证码生成工具类

/**
 * 功能:验证码生成工具类
 */
package com.ascent.util;

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;

/**
 * 功能:编写验证码生成的工具类
 *  1.获取随机字符串
 *  2.将字符串转换成图像
 * @author zmy
 * */
public class AuthImg {
	//定义随机字符串中随机出现的字符 a-z 0-9
    private static char mapTable[] = 
    { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u','v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7','8', '9' };

	/**获取随机字符串
	 * @return 随机的字符串
	 * */
    public static String random(){
    	String str="";
    	//生成5位验证码
    	for(int i=0;i<5;++i){
    		str+=mapTable[(int)(mapTable.length*Math.random())];
    	}
    	return str;
    }
    
    /**获取随机颜色对象
     * @return 随机颜色
     * */
    private static Color getRandomColor(){
    	Color col=null;
    	Random r=new Random();
    	col=new Color(r.nextInt(180),r.nextInt(180),r.nextInt(180));
    	
    	return col;
    }
    
    //将随机字符串转换成图像写到输出流
    //num-->随机字符串 out-->输出流 width-->图片宽度  height-->图片高度
    public static void imageOut(String num,OutputStream out,
    		int width,int height) throws IOException{
    	//定义缓冲区图像 rndImg
    	BufferedImage rndImg=null;
    	rndImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
    	//定义二维图像画笔对象g
    	Graphics2D g=(Graphics2D)rndImg.getGraphics();
    	//设置矩形填充颜色
    	g.setColor(Color.white);
    	//画一个 宽 高 为 的矩形
    	g.fillRect(0, 0, width, height);
    	//设置显示字体与字体类型  大小
    	Font mFont=new Font("Tahoma",Font.BOLD,height*4/5);
    	g.setFont(mFont);
    	g.setColor(Color.black);//设置默认字体颜色
    	
    	String[] str1=new String[5];
    	for(int i=0;i<str1.length;i++){
    		//绘制验证码字符
    		str1[i]=""+num.charAt(i);
    		g.setColor(getRandomColor());
    		g.drawString(str1[i], 15*i+5, height*4/5);
    		
    	}
    	//设置干扰线
    	g.setColor(Color.LIGHT_GRAY);
    	Random random=new Random();
    	for(int i=0;i<50;i++){
    		int x1=random.nextInt(width);
    		int y1=random.nextInt(height);
    		int x2=random.nextInt(10);
    		int y2=random.nextInt(10);
    		//在点(x1,y1) (x2,y2)之间画一条线
    		g.drawLine(x1, y1, x1+x2,y1+y2 );
    	}
    	//绘制外边框
    	g.drawRect(0, 0, width-1, height-1);
    	//释放画笔
    	g.dispose();
    	//将一个图像写入OutputStream
    	//rndImg 要写入的图像缓冲区对象;jpg是图片格式
    	//out 将在其中写入数据的OutputStream
    	//将内存图像写出到输出流
    	ImageIO.write(rndImg, "jpg", out);
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值