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;
}
--------------------- 

原文地址:https://www.cnblogs.com/ly570/p/11154022.html