/**
* 功能:验证码生成工具类
*/
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);
}
}
随机验证码生成工具类
最新推荐文章于 2021-03-09 14:48:24 发布