package com.hanhanfilm.common.captcha.bean;
import com.hanhanfilm.common.captcha.CaptchaUtils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* https://www.hanhanfilm.com
* Created by badouyuren.
*/
public class BaseCaptcha implements Captcha {
protected final int imgWidth;
protected final int imgHeight;
protected final BufferedImage captchaImage;
protected final int randomCodeNum;// 随机生成字符数量
protected final int RANDOM_CODE_MIN_NUM = 4;// 随机生成字符最小数量
protected final String randomCode;//生成的随机码
protected final String md5RandomCode;//md5散列后的随机码
protected BaseCaptcha(int randomCodeNum) {
if (randomCodeNum < RANDOM_CODE_MIN_NUM) {
randomCodeNum = RANDOM_CODE_MIN_NUM;
}
String className = getClass().getSimpleName();
if (className.equals("ColorfulCaptcha")) {
this.imgWidth = 16 * randomCodeNum + 12;
this.imgHeight = 26;
}else if(className.equals("JfinalCaptcha")){
this.imgWidth = 23 * randomCodeNum + 12;
this.imgHeight = 40;
}else{
this.imgWidth = 27 * randomCodeNum + 12;
this.imgHeight = 40;
}
this.randomCodeNum = randomCodeNum;
this.randomCode = generateRandomCode();
this.md5RandomCode = CaptchaUtils.encrypt(randomCode);
this.captchaImage = drawGraphic();
}
/**
* 依据字典生成随即码
* 该方法需要由子类来实现
* @return 随机码
*/
public String generateRandomCode() {
return null;
}
/**
* 依据字典生成随即码
* 该方法需要由子类来实现
* @return 随机码
*/
@Override
public BufferedImage drawGraphic() {
return null;
}
/**
* 获得生成的验证码的md5值
*
* @return 随机码
*/
@Override
public String getMd5RandomCode() {
return this.md5RandomCode;
}
/**
* 获得生成的验证码图片流
*
* @return 验证码图片流
*/
@Override
public BufferedImage getCaptchaImage() {
return captchaImage;
}
/**
* 生成随机颜色
*
* @param fc
* @param bc
* @return 颜色对象
*/
public 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);
}
/**
* 随机产生定义的颜色
*
* @return
*/
public Color getRandomColor() {
Random random = new Random();
Color color[] = new Color[10];
color[0] = new Color(32, 158, 25);
color[1] = new Color(218, 42, 19);
color[2] = new Color(31, 75, 208);
return color[random.nextInt(3)];
}
/**
* 产生随机字体
*
* @return
*/
public Font getRandomFont() {
Random random = new Random();
Font[] font = new Font[]{
new Font("nyala", Font.BOLD, 38),
new Font("Arial", Font.BOLD, 32),
new Font("Bell MT", Font.BOLD, 32),
new Font("Credit valley", Font.BOLD, 34),
new Font("Impact", Font.BOLD, 32),
new Font(Font.MONOSPACED, Font.BOLD, 40)
};
return font[random.nextInt(6)];
}
}