public class ImageUtils {
/**
* 验证码
*/
private String picCode;
public String getPicCode(){
return this.picCode;
}
/**
* 图像
* @return image
*/
public BufferedImage checkImage(){
//创建一个宽150、高40,且不带透明色的图像
final int width = 150;
final int height = 40;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取用于处理图形上下文的对象,相当于画笔
Graphics g=image.getGraphics();
//创建随机对象
Random random = new Random();
//设置图像的背景色
g.setColor(getRandomColor(180,255));
//填充矩形,坐标(0,0),宽度150,高度40
g.fillRect(0,0,width,height);
//设置字体格式
g.setFont(new Font("Times New Roman", Font.ITALIC,24));
//设置干扰线
for(int i=0;i<150;i++){
int x=random.nextInt(width);
int y=random.nextInt(height);
int x1=random.nextInt(15);
int y1=random.nextInt(15);
g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
g.drawLine(x,y,x+x1,y+y1);
}
//定义验证码字符数组
char[] ch="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
int index;
StringBuffer sb=new StringBuffer();
//取出4个数字作为验证码
for (int i=0;i<4;i++){
//循环4次随机取长度定义为索引
index=random.nextInt(ch.length);
//设置字体颜色
g.setColor(new Color(random.nextInt(55), random.nextInt(155), random.nextInt(255)));
//将验证码一次画到图像上,坐标为(x=i*18+10,y=30)
g.drawString(ch[index]+" ",(i*30+20),(random.nextInt(20)+20));
sb.append(ch[index]);
}
//赋值验证码
picCode=sb.toString();
//图像生效
g.dispose();
//赋值图像
return image;
}
/**
* 生成随机颜色
*/
public Color getRandomColor(int fc,int bc){
Random random=new Random();
if (fc>255){
fc=255;
}
if (bc>255){
bc=255;
}
//设置0-255之间的随机颜色值
int r=fc+random.nextInt(bc-fc);
int g=fc+random.nextInt(bc-fc);
int b=fc+random.nextInt(bc-fc);
//返回具有指定红色、绿色和蓝色值的不透明的sRGB颜色
return new Color(r,g,b);
}
}
在Controller 层将图像
ImageIO.write(image,"JPG",response.getOutputStream());
将验证码
request.getSession().setAttribute("piccode",picCode);
JSP页面:
<img src="<%=request.getContextPath()%>/verifyCode" id="picCode" οnclick="reloadCode();">
“/verifyCode”是请求后台的url,reloadCode()是刷新验证码
//更换验证码 function reloadCode() { var time = new Date().getTime(); document.getElementById("picCode").src = "verifyCode?d=" + time; }