使用java生成字母验证码
本文实例为大家分享了java生成字母验证码的具体代码,供大家参考,具体内容如下
importjava.awt.BasicStroke;
importjava.awt.Color;
importjava.awt.Font;
importjava.awt.Graphics2D;
importjava.awt.image.BufferedImage;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Random;
importjavax.imageio.ImageIO;
publicclassVerifyCode{
//图片宽高
privateintw=70;
privateinth=35;
privateRandomr=newRandom();
privateString[]fontNames={"宋体","华文楷体","黑体","微软雅黑","楷体_GB2312"};
privateStringcodes="234567890qwertyuipasdfghjkzxcvbnmQWERTYUIPASDFGHJKZXCVBNM";
privateColorbgColor=newColor(255,255,255);
privateStringtext;
//生成随机颜色
privateColorrandomColor(){
intred=r.nextInt(150);
intgreen=r.nextInt(150);
intblue=r.nextInt(150);
returnnewColor(red,green,blue);
}
//生成随机字体
privateFontrandomFont(){
intindex=r.nextInt(fontNames.length);
StringfontName=fontNames[index];
intstyle=r.nextInt(4);//0无1粗体2斜体3粗+斜
intsize=r.nextInt(5)+24;//生成随机字号24~28
returnnewFont(fontName,style,size);
}
//干扰线
privatevoiddrowLine(BufferedImageimage){
//生成4条干扰线
intnum=4;
Graphics2Dbi=(Graphics2D)image.getGraphics();
for(inti=0;i<num;i++){
intx1=r.nextInt(w);
intx2=r.nextInt(w);
inty1=r.nextInt(h);
inty2=r.nextInt(h);
bi.setStroke(newBasicStroke(1.5F));
bi.setColor(Color.BLUE);//干扰线色
bi.drawLine(x1,y1,x2,y2);
}
}
//随机生成一个字符
privatecharrandomChar(){
intindex=r.nextInt(codes.length());
returncodes.charAt(index);
}
//图片缓冲区
privateBufferedImagecreateImage(){
BufferedImageimage=newBufferedImage(w,h,BufferedImage.TYPE_INT_BGR);
Graphics2Dbi=(Graphics2D)image.getGraphics();
bi.setColor(this.bgColor);
bi.fillRect(0,0,w,h);
returnimage;
}
//生成图片
publicBufferedImagegetImage(){
BufferedImageimage=createImage();
Graphics2Dbi=(Graphics2D)image.getGraphics();
StringBuildersb=newStringBuilder();
for(inti=0;i<4;i++){
Stringstring=randomChar()+"";
sb.append(string);
//每个字符占图片1/4宽
floatx=i*1.0F*w/4;
//随机字体格式
bi.setFont(randomFont());
bi.setColor(randomColor());
//把字写在图片适当处(h-6指图片距底部6个高度)
bi.drawString(string,x,h-6);
}
this.text=sb.toString();
drowLine(image);
returnimage;
}
//返回得到的字体
publicStringgetText(){
returntext;
}
//把图片写入指定位置
publicstaticvoidoutput(BufferedImageimage,OutputStreamout){
try{
ImageIO.write(image,"JPG",out);
}catch(IOExceptione){
e.printStackTrace();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。