<dependency>
<groupId>net.pusuo</groupId>
<artifactId>patchca</artifactId>
<version>0.5.0</version>
<scope>compile</scope>
</dependency>
import org.apache.commons.codec.binary.Base64;
import org.patchca.background.BackgroundFactory;
import org.patchca.color.SingleColorFactory;
import org.patchca.filter.predefined.CurvesRippleFilterFactory;
import org.patchca.service.Captcha;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.word.RandomWordFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* 启动程序
*/
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class Application
{
private static final ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
static {
//设置字体颜色
cs.setColorFactory(new SingleColorFactory(new Color(139, 83, 246)));
cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
//设置字体颜色
cs.setWidth(130);
cs.setHeight(60);
RandomWordFactory randomWordFactory = new RandomWordFactory();
randomWordFactory.setMaxLength(4);
randomWordFactory.setMinLength(4);
cs.setWordFactory(randomWordFactory);
//设置背景颜色
cs.setBackgroundFactory( new BackgroundFactory() {
@Override
public void fillBackground(BufferedImage image) {
Graphics graphics = image.getGraphics();
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();
graphics.setColor(new Color(44, 44, 44));
graphics.fillRect(0, 0, imgWidth, imgHeight);
//可以设置 噪点 干扰线。。。。
}
});
}
public static void main(String[] args) throws IOException {
Captcha captcha = cs.getCaptcha();
ByteArrayOutputStream outputStream = null;
outputStream = new ByteArrayOutputStream();
String msgId = captcha.getChallenge();
ImageIO.write(captcha.getImage(), "png", outputStream);
String images = "data:image/jpg;base64," + Base64.encodeBase64String(outputStream.toByteArray());
//图片编码
System.out.println(images);
//图片校验用id
System.out.println(msgId);
}
}
生成随机数
public static String getRandom(Jedis jedis,Integer leg,String prefix) {
String str = "";
Random rand = new Random();
for(int i=0;i<leg;i++){
int num = rand.nextInt(3);
switch(num){
case 0:
char c1 = (char)(rand.nextInt(26)+'a');//生成随机小写字母
str += c1;
break;
case 1:
char c2 = (char)(rand.nextInt(26)+'A');//生成随机大写字母
str += c2;
break;
case 2:
str += rand.nextInt(10);//生成随机数字
break;
default:
str += rand.nextInt(10);//生成随机数字
}
}
String res = jedis.get(prefix + str);
if(StringUtils.isNotEmpty(res)){
return getRandom(jedis,leg,prefix);
}
return str;
}
测试
// 将 data 换成 images 输出值,就可以看到了
<div class="col-sm-3"> <img class="googleQrcode" style="width: 100px" src="data"></div>