java 验证码生成工具类_Java生成图形验证码工具类

生成验证码效果

717c2703a8fb865d794bb3253ddb49a0.png

validatecode.java 验证码生成类

package cn.dsna.util.images;

import java.awt.color;

import java.awt.font;

import java.awt.graphics2d;

import java.awt.image.bufferedimage;

import java.io.fileoutputstream;

import java.io.ioexception;

import java.io.outputstream;

import java.util.random;

import javax.imageio.imageio;

/**

* 验证码生成器

* @author dsna

*

*/

public class validatecode {

// 图片的宽度。

private int width = 160;

// 图片的高度。

private int height = 40;

// 验证码字符个数

private int codecount = 5;

// 验证码干扰线数

private int linecount = 150;

// 验证码

private string code = null;

// 验证码图片buffer

private bufferedimage buffimg=null;

private char[] codesequence = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',

'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',

'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

public validatecode() {

this.createcode();

}

/**

*

* @param width 图片宽

* @param height 图片高

*/

public validatecode(int width,int height) {

this.width=width;

this.height=height;

this.createcode();

}

/**

*

* @param width 图片宽

* @param height 图片高

* @param codecount 字符个数

* @param linecount 干扰线条数

*/

public validatecode(int width,int height,int codecount,int linecount) {

this.width=width;

this.height=height;

this.codecount=codecount;

this.linecount=linecount;

this.createcode();

}

public void createcode() {

int x = 0,fontheight=0,codey=0;

int red = 0, green = 0, blue = 0;

x = width / (codecount +2);//每个字符的宽度

fontheight = height - 2;//字体的高度

codey = height - 4;

// 图像buffer

buffimg = new bufferedimage(width, height,bufferedimage.type_int_rgb);

graphics2d g = buffimg.creategraphics();

// 生成随机数

random random = new random();

// 将图像填充为白色

g.setcolor(color.white);

g.fillrect(0, 0, width, height);

// 创建字体

imgfontbyte imgfont=new imgfontbyte();

font font =imgfont.getfont(fontheight);

g.setfont(font);

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

int xs = random.nextint(width);

int ys = random.nextint(height);

int xe = xs+random.nextint(width/8);

int ye = ys+random.nextint(height/8);

red = random.nextint(255);

green = random.nextint(255);

blue = random.nextint(255);

g.setcolor(new color(red, green, blue));

g.drawline(xs, ys, xe, ye);

}

// randomcode记录随机产生的验证码

stringbuffer randomcode = new stringbuffer();

// 随机产生codecount个字符的验证码。

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

string strrand = string.valueof(codesequence[random.nextint(codesequence.length)]);

// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。

red = random.nextint(255);

green = random.nextint(255);

blue = random.nextint(255);

g.setcolor(new color(red, green, blue));

g.drawstring(strrand, (i + 1) * x, codey);

// 将产生的四个随机数组合在一起。

randomcode.append(strrand);

}

// 将四位数字的验证码保存到session中。

code=randomcode.tostring();

}

public void write(string path) throws ioexception {

outputstream sos = new fileoutputstream(path);

this.write(sos);

}

public void write(outputstream sos) throws ioexception {

imageio.write(buffimg, "png", sos);

sos.close();

}

public bufferedimage getbuffimg() {

return buffimg;

}

public string getcode() {

return code;

}

}

imgfontbyte.java

package cn.dsna.util.images;

import java.io.bytearrayinputstream;

import java.awt.*;

/**

* ttf字体文件

* @author dsna

*

*/

public class imgfontbyte {

public font getfont(int fontheight){

try {

font basefont = font.createfont(font.truetype_font, new bytearrayinputstream(hex2byte(getfontbytestr())));

return basefont.derivefont(font.plain, fontheight);

} catch (exception e) {

return new font("arial",font.plain, fontheight);

}

}

private byte[] hex2byte(string str) {

if (str == null)

return null;

str = str.trim();

int len = str.length();

if (len == 0 || len % 2 == 1)

return null;

byte[] b = new byte[len / 2];

try {

for (int i = 0; i < str.length(); i += 2) {

b[i / 2] = (byte) integer

.decode("0x" + str.substring(i, i + 2)).intvalue();

}

return b;

} catch (exception e) {

return null;

}

} /**

* ttf字体文件的十六进制字符串

* @return

*/

private string getfontbytestr(){ return null;

return str;//字符串太长 在附件中找

}

}

validatecodeservlet.java servlet调用方法

package cn.dsna.util.images;

import java.io.ioexception;

import javax.servlet.servletexception;

import javax.servlet.http.httpservlet;

import javax.servlet.http.httpservletrequest;

import javax.servlet.http.httpservletresponse;

import javax.servlet.http.httpsession;

public class validatecodeservlet extends httpservlet {

private static final long serialversionuid = 1l;

@override

protected void doget(httpservletrequest reqeust,

httpservletresponse response) throws servletexception, ioexception {

// 设置响应的类型格式为图片格式

response.setcontenttype("image/jpeg");

//禁止图像缓存。

response.setheader("pragma", "no-cache");

response.setheader("cache-control", "no-cache");

response.setdateheader("expires", 0);

httpsession session = reqeust.getsession();

validatecode vcode = new validatecode(120,40,5,100);

session.setattribute("code", vcode.getcode());

vcode.write(response.getoutputstream());

}

/**

* web.xml 添加servlet

validatecodeservlet

cn.dsna.util.images.validatecodeservlet

validatecodeservlet

*.images

在地址栏输入xxx/dsna.images 测试

*/

}

测试类

validatecodetest.java

package cn.dsna.util.images;

import java.io.ioexception;

import java.util.date;

public class validatecodetest {

/**

* @param args

*/

public static void main(string[] args) {

validatecode vcode = new validatecode(120,40,5,100);

try {

string path="d:/t/"+new date().gettime()+".png";

system.out.println(vcode.getcode()+" >"+path);

vcode.write(path);

} catch (ioexception e) {

e.printstacktrace();

}

}

}

web.xml 配置

validatecodeservlet

cn.dsna.util.images.validatecodeservlet

validatecodeservlet

*.images

以上所述是小编给大家介绍的java生成图形验证码工具类,希望对大家有所帮助

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java生成图形验证码工具类很多,其中比较常用的是使用第三方库生成验证码图片,比如Google的kaptcha和阿里巴巴的GifCaptcha等。 以下是一个使用kaptcha生成图形验证码的示例代码: ```java import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.util.Properties; public class CaptchaUtils { private static DefaultKaptcha captchaProducer; static { captchaProducer = new DefaultKaptcha(); Properties properties = new Properties(); // 设置验证码图片的宽度 properties.setProperty("kaptcha.image.width", "120"); // 设置验证码图片的高度 properties.setProperty("kaptcha.image.height", "40"); // 设置验证码字符的字体 properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier"); // 设置验证码字符个数 properties.setProperty("kaptcha.textproducer.char.length", "4"); Config config = new Config(properties); captchaProducer.setConfig(config); } public static BufferedImage generateCaptcha(String text) { return captchaProducer.createImage(text); } public static byte[] generateCaptchaBytes(String text) { try { BufferedImage image = captchaProducer.createImage(text); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(image, "png", outputStream); return outputStream.toByteArray(); } catch (Exception e) { e.printStackTrace(); return null; } } } ``` 使用示例: ```java // 生成验证码图片 BufferedImage image = CaptchaUtils.generateCaptcha("abcd"); // 将验证码图片转换成字节数组 byte[] bytes = CaptchaUtils.generateCaptchaBytes("abcd"); ``` 这个工具类使用了kaptcha库,可以方便地生成图形验证码图片。可以通过修改配置文件来定制验证码图片的样式和字符个数等参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值