先上效果圖 下面直接上代碼
1、maven 依賴
<dependency>
<groupId>com.github.bingoohuang</groupId>
<artifactId>patchca</artifactId>
<version>0.0.1</version>
</dependency>
2、創建生成驗證碼工具類
import com.github.bingoohuang.patchca.color.ColorFactory;
import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;
import com.github.bingoohuang.patchca.filter.predefined.*;
import com.github.bingoohuang.patchca.utils.encoder.EncoderHelper;
import com.github.bingoohuang.patchca.word.RandomWordFactory;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.Random;
/**
* @author WangDong
* @description java生成驗證碼工具類
* 創建時間:2019-09-19
*/
public class CaptChaUtil {
private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
private static Random random = new Random();
static {
//設置驗證碼字符顏色
cs.setColorFactory(new ColorFactory() {
@Override
public Color getColor(int x) {
int[] c = new int[3];
int i = random.nextInt(c.length);
for (int fi = 0; fi < c.length; fi++) {
if (fi == i) {
c[fi] = random.nextInt(71);
} else {
c[fi] = random.nextInt(256);
}
}
return new Color(c[0], c[1], c[2]);
}
});
RandomWordFactory wf = new RandomWordFactory();
wf.setCharacters("abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ");
wf.setMaxLength(5);//最大驗證碼個數
wf.setMinLength(5);//最小驗證碼個數
cs.setWordFactory(wf);
}
public static String getValidCode(HttpServletResponse response) {
//生成不同風格的驗證碼
switch (random.nextInt(5)) {
case 0:
cs.setFilterFactory(new CurvesRippleFilterFactory(cs
.getColorFactory()));
break;
case 1:
cs.setFilterFactory(new MarbleRippleFilterFactory());
break;
case 2:
cs.setFilterFactory(new DoubleRippleFilterFactory());
break;
case 3:
cs.setFilterFactory(new WobbleRippleFilterFactory());
break;
case 4:
cs.setFilterFactory(new DiffuseRippleFilterFactory());
break;
}
setResponseHeaders(response);
String captCha = "";
try{
captCha = EncoderHelper.getChallangeAndWriteImage(cs, "png",response.getOutputStream());
}catch (IOException i){
}
return captCha;
}
protected static void setResponseHeaders(HttpServletResponse response) {
response.setContentType("image/png");
response.setHeader("Cache-Control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
long time = System.currentTimeMillis();
response.setDateHeader("Last-Modified", time);
response.setDateHeader("Date", time);
response.setDateHeader("Expires", time);
}
}
3、調用接口
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/validCode/")
public class ValidCode {
@PostMapping(value = "captcha")
public JSONObject captcha(HttpServletResponse response){
String token = CaptChaUtil.getValidCode(response);
JSONObject object = new JSONObject();
object.put("validCode", token);
return object;
}
}
4、效果圖