import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* @author dell Brittany ln
*
*/
public class TestCapth {
private static final int EXIT_ON_CLOSE = 0;
private int width = 100;//设置验证码区的宽度
private int height = 40;//设置长度
private int length = 4;//设置验证码长度
private final String strs="asdm412cjdlufohsazss87536";//设置字符串public BufferedImage getImage(){
//创建bufferedimage缓冲区
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//创建画笔Graphics g = img.getGraphics();
//设置背景颜色g.setColor(getRandomColor(90,250));
//填充验证码区颜色g.fillRect(0, 0, width, height);
//设置边框颜色
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
Random rands = new Random();
for(int i=0;i<4;i++){//设置字体
g.setFont(new Font("楷体", Font.HANGING_BASELINE, 24));
g.setColor(getRandomColor(90, 255));//设置字体颜色
String ss = String.valueOf(strs.charAt(rands.nextInt(length)));//随机获取字符串
int y = (int) (Math.random()*30+10);//使用随机数改变y的坐标
int x = (int) (Math.random()*60+10);//使用随机数改变x的坐标
g.drawString(ss, x, y);//画出字符串}
//画干扰线
drawLine(g,10);
g.dispose();//释放资源
return img;}
//画干扰线
private void drawLine(Graphics g, int i) {
Random rand = new Random();
for(int j=0;j<10;j++){
g.setColor(getRandomColor(80, 200));
// 生成随机线条起点终点坐标点
int x1 = rand.nextInt(this.width);//起点的x坐标
int y1 = rand.nextInt(this.height);//起点的y坐标
int x2 = rand.nextInt(this.width);//终点的x坐标
int y2 = rand.nextInt(this.height);//终点的y坐标// 画线条
g.drawLine(x1, y1, x2, y2);
}
}
/**
* 设置颜色
* @param max 上限
* @param min 下限
* @return
*/
private Color getRandomColor(int max, int min) {
if(min>max){
int temp = min;
min = max;
max = temp;
}
if(max>255){
max=255;
}
if(min<0){
min=0;
}
int r = (int)(Math.random()*(max-min));
int g = (int)(Math.random()*(max-min));
int b = (int)(Math.random()*(max-min));
return new Color(r, g, b);
}
public static void main(String[] args) {
TestCapth capth = new TestCapth();JFrame jf = new JFrame("验证码");//使用JFrame使用和设置窗体
jf.setSize(300, 200);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);JLabel lab = new JLabel(new ImageIcon(capth.getImage()));
jf.add(lab);
jf.setVisible(true);}
}
/* *****************************************效果图显示***************************************** */
(1)
(2)