RandomCode工具类
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class RandomCode {
public static String strCode = null;
static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
static Random random = new Random();
private static int codeLength = 4;
private static int noisePoint = 100;
public static String getRandomString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < codeLength; i++) {
buffer.append(CHARS[random.nextInt(CHARS.length)]);
}
strCode = buffer.toString();
return strCode;
}
public static Color getRandomColor() {
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
public static Color getReverseColor(Color c) {
return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
}
public BufferedImage createImage() {
String randomString = getRandomString();
int width = 80;
int height = 30;
Color color = getRandomColor();
Color reverse = getReverseColor(color);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 23));
g.setColor(color);
g.fillRect(0, 0, width, height);
g.setColor(reverse);
g.drawString(randomString, 5, 23);
for (int i = 0, n = random.nextInt(noisePoint); i < n; i++) {
g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
}
return image;
}
}
Controller层
@RestController
@RequestMapping("/v2")
public class ZipController {
@GetMapping("/getGifCode")
public void getGifCode(HttpServletResponse response, HttpServletRequest request) {
RandomCode rc = new RandomCode();
BufferedImage image = rc.createImage();
String randomcode = RandomCode.strCode;
request.getSession().setAttribute("_code", randomcode.toLowerCase());
try {
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "JPEG", outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
前端
<div class="in">
<div class="in-label">验证码</div>
<div class="in-text flex flex-c-b">
<input id="verifyCode" class="text small" placeholder="请输入验证码" type="text"/>
<img id="refreshCode" src="${ctx }/merchant/${exhibitionId}/getGifCode" class="code cursor" alt=""/>
</div>
</div>