文件结构
1.创建一个存储验证码信息的类,用于校验,这里不做校验,这个类意义不大
import java.awt.image.BufferedImage;
public class GraphicCode {
private BufferedImage image;
private String code;
public GraphicCode(BufferedImage image, String code) {
this.image = image;
this.code = code;
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
2.创建图形验证码的生成器
public class GraphicCodeGenerator {
private Color[] colors = {new Color(245, 245, 245), new Color(143, 188, 143),
new Color(122, 139, 139), new Color(122, 197, 205)};
public GraphicCode createGraphicCode(){
int width = 100;
int height = 30;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
Random random = new Random();
graphics.setColor(colors[random.nextInt(4)]);
graphics.fillRect(0, 0, width, height);
for (int i = 0; i < 5; i++){
graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
}
StringBuilder sb = new StringBuilder();
graphics.setFont(new Font("Arial", Font.CENTER_BASELINE, 17));
for (int i = 0; i < 4; i++){
String num = String.valueOf(random.nextInt(10));
sb.append(num);
graphics.setColor(new Color(random.nextInt(250), random.nextInt(250), random.nextInt(250)));
graphics.drawString(num, width / 4 * i + 10, 20);
}
return new GraphicCode(bufferedImage, sb.toString());
}
}
3.写一个控制器
import com.dfyang.graphic.graphicCode.GraphicCode;
import com.dfyang.graphic.graphicCode.GraphicCodeGenerator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class IndexController {
@GetMapping("/index")
public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
GraphicCodeGenerator graphicCodeGenerator = new GraphicCodeGenerator();
GraphicCode graphicCode = graphicCodeGenerator.createGraphicCode();
ImageIO.write(graphicCode.getImage(), "JPEG", response.getOutputStream());
}
}
4.写一个html看看验证码怎么样
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图形验证码</title>
</head>
<body>
<img src="/index">
</body>
</html>
运行结果——