Java实现动态获取图片验证码的示例代码
本文介绍了Java实现动态获取图片验证码的示例代码,分享给大家,具体如下:
importjavax.imageio.ImageIO;
importjava.awt.*;
importjava.awt.image.BufferedImage;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.io.UnsupportedEncodingException;
importjava.util.Random;
publicclassImgAuthCode{
/**
*图片的宽度
*/
privateintwidth=330;
/**
*图片的高度
*/
privateintheight=40;
/**
*验证码字符个数
*/
privateintcodeCount=5;
/**
*验证码干扰线数
*/
privateintlineCount=150;
/**
*图片验证码类型
*/
privateImgCodeTypeimgCodeType=DEFAULT_TYPE;
/**
*验证码
*/
privateStringcode=null;
/**
*验证码图片Buffer
*/
privateBufferedImagebuffImg=null;
privatestaticfinalImgCodeTypeDEFAULT_TYPE=ImgCodeType.ENANDNUMBER;
privatestaticchar[]codeSequence={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R',
'S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9'};
publicImgAuthCode(){
this.createCode();
}
/**
*@paramwidth图片宽
*@paramheight图片高
*/
publicImgAuthCode(intwidth,intheight){
this.width=width;
this.height=height;
this.createCode();
}
/**
*@paramwidth图片宽
*@paramheight图片高
*@paramcodeCount字符个数
*@paramlineCount干扰线条数
*/
publicImgAuthCode(intwidth,intheight,intcodeCount,intlineCount,ImgCodeTypeimgCodeType){
this.width=width;
this.height=height;
this.codeCount=codeCount;
this.lineCount=lineCount;
this.imgCodeType=imgCodeType;
this.createCode();
}
publicvoidcreateCode(){
intx=0,fontHeight=0,codeY=0;
x=width/(codeCount+2);//每个字符的宽度
fontHeight=height-2;//字体的高度
codeY=height-4;
//图像buffer
buffImg=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2Dg=buffImg.createGraphics();
//将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0,0,width,height);
//创建字体
//ImgFontByteimgFont=newImgFontByte();
//Fontfont=imgFont.getFont(fontHeight);
Fontfont=newFont("微软雅黑",Font.PLAIN,fontHeight);
g.setFont(font);
drawRandomLine(g);
//randomCode记录随机产生的验证码
StringBufferrandomCode=newStringBuffer();
//随机产生codeCount个字符的验证码。
for(inti=0;i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。