一次性验证码的代码实现

关于产生一个一次性验证码的代码如下

 

public class CheckImgServlet extends HttpServlet {

 

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int width = 120;

int height = 30;

BufferedImage bufferedImage = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

 

Graphics graphics = bufferedImage.getGraphics();

graphics.setColor(getRandColor(200, 250));

graphics.fillRect(0, 0, width, height);

 

graphics.setColor(Color.WHITE);

graphics.drawRect(0, 0, width - 1, height - 1);

 

Graphics2D graphics2d = (Graphics2D) graphics;

graphics2d.setFont(new Font("瀹嬩綋", Font.BOLD, 18));

 

String words =

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

Random random = new Random();

StringBuffer buffer = new StringBuffer();

int x = 10;

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

graphics2d.setColor(new Color(20 + random.nextInt(110), 20 + random

.nextInt(110), 20 + random.nextInt(110)));

// 鏃嬭浆 -30 --- 30搴�

int jiaodu = random.nextInt(60) - 30;

// 鎹㈢畻寮у害

double theta = jiaodu * Math.PI / 180;

 

// 鐢熸垚涓�涓殢鏈烘暟瀛�

int index = random.nextInt(words.length()); // 鐢熸垚闅忔満鏁� 0 鍒� length - 1

// 鑾峰緱瀛楁瘝鏁板瓧

char c = words.charAt(index);

// 灏嗛殢鏈轰骇鐢熺殑瀛楃瀛樺叆鍒板瓧绗︿覆涓�:

buffer.append(c);

// 灏哻 杈撳嚭鍒板浘鐗�

graphics2d.rotate(theta, x, 20);

graphics2d.drawString(String.valueOf(c), x, 20);

graphics2d.rotate(-theta, x, 20);

x += 30;

}

// 灏哹uffer垚瀛楃涓插璞★細

String checkcode = buffer.toString();

// 灏嗗叾瀛樺叆鍒皊ession

request.getSession().setAttribute("checkcode", checkcode);

// 姝ラ浜� 缁樺埗骞叉壈绾�

graphics.setColor(getRandColor(160, 200));

int x1;

int x2;

int y1;

int y2;

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

x1 = random.nextInt(width);

x2 = random.nextInt(12);

y1 = random.nextInt(height);

y2 = random.nextInt(12);

graphics.drawLine(x1, y1, x1 + x2, x2 + y2);

}

 

// 灏嗕笂闈㈠浘鐗囪緭鍑哄埌娴忚鍣� ImageIO

graphics.dispose();// 閲婃斁璧勬簮

ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

 

}

 

 

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

private Color getRandColor(int fc, int bc) {

// 鍙栧叾闅忔満棰滆壊

Random random = new Random();

if (fc > 255) {

fc = 255;

}

if (bc > 255) {

bc = 255;

}

int r = fc + random.nextInt(bc - fc);

int g = fc + random.nextInt(bc - fc);

int b = fc + random.nextInt(bc - fc);

return new Color(r, g, b);

}

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值