java 后台验证码_java 后台 实现简单的验证码

private int width =80;

private int height=30;

private Random r=new Random();

private String fontnames[]= {"宋体","华文楷体","黑体","微软雅黑","楷体_GBK2312"};

private String Codes="23456789QWERTYUOPASDFGHJKLZXCVBNMqwertyuopasdfghjklzxcvbnm";

private Color color=new Color(255,255,255);

private String text;

//随机颜色

public Color setColor(){

int red = r.nextInt(150);

int grreen = r.nextInt(150);

int blue = r.nextInt(150);

return new Color(red,grreen,blue);

}

//随机字体

private Font randomFont() {

int nextInt = r.nextInt(fontnames.length);

String fontnsmr= fontnames[nextInt];

int style=r.nextInt(4);

int size=r.nextInt(5)+24;

return new Font(fontnsmr, style, size);

}

//创建图片

private BufferedImage creatrimg() {

BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics2D graphics = (Graphics2D)img.getGraphics();//得到画笔

graphics.setColor(this.color);

graphics.fillRect(0, 0, width, height);//fillRect(坐标,坐标,width,height)

return img;

}

//生成随机字符

private char randomChar() {

int r=this.Codes.length();

int index=this.r.nextInt(r);

char c=this.Codes.charAt(index);

return c;

}

//添加干扰线

private void drawLine(BufferedImage bfimg) {

Graphics2D graphics = (Graphics2D)bfimg.getGraphics();

for (int i = 0; i <3; i++) {

graphics.setStroke(new BasicStroke(1f));

graphics.setColor(Color.BLUE);

graphics.drawLine(r.nextInt(width), r.nextInt(height),r.nextInt(width),r.nextInt(height));

}

}

//得到验证码

public BufferedImage getimg() {

//创建图片缓冲区

BufferedImage bfimg=creatrimg();

//得到画笔

Graphics2D graphics = (Graphics2D)bfimg.getGraphics();

//装载生成的验证码

StringBuffer sb=new StringBuffer();

//向图片绘制四个字符

for (int i = 1; i < 5; i++) {

String randomChar = randomChar()+"";

sb.append(randomChar);

//设置当前字符的x 轴

float x=i*1.0f*width/5;

//设置随机字体

graphics.setFont(randomFont());

graphics.setColor(randomColor());

graphics.drawString(randomChar, x, height-=2);

}

this.text=sb.toString(http://www.my516.com);

//添加干扰线

drawLine(bfimg);

return bfimg;

}

---------------------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值