您的位置:首页 > 编程语言 > Java开发

java获得验证码图片

2015-08-06 18:14 363 查看
基本思想:

1、获得文本信息

2、将生成的文本画在图片上

3、调用方法把内存流给客户端

代码如下:

(1)生成文本信息

import java.util.Arrays;

/**

*

*@author yang

*@类功能说明:随机生成验证码值:验证码串

*@修改日期:2015-6-27 下午04:02:49

*@创建时间:2015-6-27 下午04:02:49

*@版本:V1.0

*/

public class ValidateCode {

/**

* 验证码难度级别 Simple-数字 Medium-数字和小写字母 Hard-数字和大小写字母

*/

public enum SecurityCodeLevel {

Simple, Medium, Hard

};

/**

* 产生默认验证码,4位中等难度

*

* @return

*/

public static String getSecurityCode() {

return getSecurityCode(4, SecurityCodeLevel.Medium, false);

}

/**

* 产生长度和难度任意的验证码

*

* @param length

* @param level

* @param isCanRepeat

* @return

*/

public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {

// 随机抽取len个字符

int len = length;

// 字符集合(–除去易混淆的数字0,1,字母l,o,O)

char[] codes = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
// 根据不同难度截取字符串
if (level == SecurityCodeLevel.Simple) {
codes = Arrays.copyOfRange(codes, 0, 10);
} else if (level == SecurityCodeLevel.Medium) {
codes = Arrays.copyOfRange(codes, 0, 36);
}
// 字符集和长度
int n = codes.length;
// 抛出运行时异常
if (len > n && isCanRepeat == false) {
throw new RuntimeException(String.format("调用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出现异常," + "当isCanRepeat为%3$s时,传入参数%1$s不能大于%4$s", len, level, isCanRepeat, n));
}
// 存放抽取出来的字符
char[] result = new char[len];

if (isCanRepeat) {
for (int i = 0; i < result.length; i++) {
// 索引0 and n-1
int r = (int) (Math.random() * n);
// 将result中的第i个元素设置为code[r]存放的数值
result[i] = codes[r];
}
} else {
for (int i = 0; i < result.length; i++) {
// 索引0 and n-1
int r = (int) (Math.random() * n);
// 将result中的第i个元素设置为code[r]存放的数值
result[i] = codes[r];
// 必须确保不会再次抽取到那个字符,这里用数组中最后一个字符改写code[r],并将n-1
codes[r] = codes[n - 1];
n--;
}
}
return String.valueOf(result);
}
public static void main(String[] args) {
//System.out.println(SecurityCode.getSecurityCode());
System.out.println(ValidateCode.getSecurityCode(5, SecurityCodeLevel.Hard, false));
}


}

(2)生成图片流

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.util.Random;

import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**

*

*@author yang

*@类功能说明:将随机字符串写在图片上

*@修改日期:2015-6-27 下午04:03:05

*@修改说明:2015

*@创建时间:2015-6-27 下午04:03:05

*@版本:V1.0

*/

public class ValidateImage {

public static BufferedImage createImage(String securityCode){
int codeLength = securityCode.length();
int fontSize = 18;
int fontWidth = fontSize+1;
int width = codeLength*fontWidth+6;
int height = fontSize*2+1;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.PINK);
g.fillRect(0, 0, width, height);
g.setColor(Color.LIGHT_GRAY);
g.setFont(new Font("Arial", Font.BOLD, height-2));
g.drawRect(0, 0, width-1, height-1);
Random rand = new Random();
g.setColor(Color.LIGHT_GRAY);

for (int i = 0; i < codeLength*6; i++) {
int x = rand.nextInt(width);
int y = rand.nextInt(height);
g.drawRect(x, y, 1, 1);
}
int codeY = height-10;
g.setColor(new Color(19,148,246));
g.setFont(new Font("Georgia", Font.BOLD, fontSize));

for(int i=0;i<codeLength;i++){
double deg=new Random().nextDouble()*20;
g.rotate(Math.toRadians(deg), i*16+13,codeY-7.5);
g.drawString(String.valueOf(securityCode.charAt(i)), i*16+5, codeY);
g.rotate(Math.toRadians(-deg), i*16+13,codeY-7.5);
}
g.dispose();
return image;
}
public static ByteArrayInputStream getImageAsInputStream(String securityCode){
BufferedImage image = createImage(securityCode);
return convertImageToStream(image);
}
public static ByteArrayInputStream convertImageToStream(BufferedImage image){
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
try {
encoder.encode(image);
byte[] b = outStream.toByteArray();
inputStream = new ByteArrayInputStream(b);
} catch (Exception e) {
}
return inputStream;
}


}

(3)获取流写给客户端显示(struts2使用)

public String getCheckCode()throws Exception{
String code = ValidateCode.getSecurityCode();
vs.setValue("#session.code", code);//存放在session中
BufferedImage bi = ValidateImage.createImage(code);
ServletOutputStream os = ServletActionContext.getResponse().getOutputStream();
ImageIO.write(bi, "jpeg", os);
return Action.NONE;


(4)客户端获得流(jsp中):

img style=”width:70px;height:30px;”

onclick=”this.src=this.src”

src=”${pageContext.request.contextPath}/getCheckCode”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: