简单验证码

package com.lovo;
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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值