本文主要是介绍带加减法的图片验证码(java编程实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近用java做了一个加法验证码,是在kaptcha的基础上改写的,而kaptcha是一个扩展自 simplecaptcha的验证码库。
- // create the text for the image
- List<String> capText = createText();
- // store the text in the session
- String sessionid = UserCookieUtil.getSessionId(request);
- cacheManager.setCode(VerifyTypeEnum.IMG_CODE, sessionid, capText.get(1), timeout);
- // create the image with the text
- BufferedImage bi = captchaProducer.createImage(capText.get(0));
- ServletOutputStream out = response.getOutputStream();
- // write the data out
- ImageIO.write(bi, "jpg", out);
- try {
- out.flush();
- } finally {
- out.close();
- }
- // create the text for the image
- private List<String> createText() {
- int intFirst, intSec, intTemp, validCodeResult;
- String validCode = null;
- Random rand = new Random();
- intFirst = (int) (Math.random() * 10);
- intSec = (int) (Math.random() * 10);
- switch (rand.nextInt(3)) {
- case 0:
- if (intFirst < intSec) {
- intTemp = intFirst;
- intFirst = intSec;
- intSec = intTemp;
- }
- validCode = intFirst + "-" + intSec + "=?";
- validCodeResult = intFirst - intSec;
- break;
- case 1:
- validCode = intFirst + "+" + intSec + "=?";
- validCodeResult = intFirst + intSec;
- break;
- default:
- validCode = intFirst + "*" + intSec + "=?";
- validCodeResult = intFirst * intSec;
- break;
- }
- List<String> list = new ArrayList<String>();
- list.add(validCode);
- list.add(String.valueOf(validCodeResult));
- return list;
- }
下面再补充几种验证码
(1)// 由0-9组成的全数字验证码
public static void numCode() {
System.out.print("获取4位数字验证码:");
for (int i = 0; i < 4; i++) {
int n = rd.nextInt(10);
System.out.print(n + " ");
}
System.out.println();
}
(2)// 英文字母和标点符号组成的字符验证码
public static void charCode() {
System.out.print("获取4位字符验证码:");
for (int i = 0; i < 4; i++) {
int n = 65 + rd.nextInt(58);
System.out.print((char) n);
}
System.out.println();
}
(3)// 全部由中文组成的验证码
public static void chineseCode() {
System.out.print("获取4位汉字验证码:");
for (int i = 0; i < 4; i++) {
int n = 20000 + rd.nextInt(10000);
System.out.print((char) n);
}
System.out.println();
}
(4)// 字符+数字的混合验证码
public static void mixCode() {
System.out.print("\n获取的5位混合验证码:");
for (int i = 0; i < 4; i++) {
int n = rd.nextInt(123);
if (n < 65) {
System.out.print(n % 10);
} else {
System.out.print((char) n);
}
}
}
这篇关于带加减法的图片验证码(java编程实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!