Java web dynamic image verification code

Verification code

  • Prevent malicious registration form

Generates CAPTCHA image

  • Defined width and height
int width = 100;
int height = 50;
  • BufferedImage and then use the memory to generate images
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  • Draw the background and border
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
  • Create a random number of random characters and objects
//字符集
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgjijklmnopqrstuvwxyz";

//随机数
Random ran = new Random();
  • Create a method for generating random colors
private Color getRandomColor(Random random) {
    //获取随机颜色
    int colorIndex = random.nextInt(3);
    switch (colorIndex) {
        case 0:
            return Color.BLUE;
        case 1:
            return Color.GREEN;
        case 2:
            return Color.RED;
        case 3:
            return Color.YELLOW;
        default:
            return Color.MAGENTA;
    }
}
  • Draw character verification code
//绘制验证码
for (int i = 0; i < 4; i++) {
    //获取随机字符
    int index = ran.nextInt(str.length());
    char ch = str.charAt(index);
    //获取随机色
    Color randomColor = getRandomColor(ran);
    g.setColor(randomColor);
    //设置字体
    Font font = new Font("宋体", Font.BOLD, height / 2);
    g.setFont(font);
    //写入验证码
    g.drawString(ch + "", (i == 0) ? width / 4 * i + 2 : width / 4 * i, height - height / 4);
}
  • Draw line interference
//干扰线
for (int i = 0; i < 10; i++) {
    int x1 = ran.nextInt(width);
    int x2 = ran.nextInt(width);
    int y1 = ran.nextInt(height);
    int y2 = ran.nextInt(height);
    Color randomColor = getRandomColor(ran);
    g.setColor(randomColor);
    g.drawLine(x1, x2, y1, y2);
}
  • Output images using ImageIO
ImageIO.write(image, "jpg", resp.getOutputStream());
  • Results Figure

Here Insert Picture Description

Refresh achieve results

  • New html page
  • Use the img tag realization Photo Gallery
<img id="identcode" src="identcode">
<a id="refesh" href="">看不清,换一张</a>
  • Refresh effect achieved using js
//点击图片时
var img = document.getElementById("identcode");
img.onclick = function (){
    refesh();
}

//点击连接时
var a = document.getElementById("refesh");
a.onclick = function (){
    refesh();
    //返回false防止a标签默认href行为
    return false;
}

function refesh() {
    /**
     * 由于路径相同时浏览器会自动调用缓存中的图片
     * 所以在连接后加时间戳解决此问题
     */
    var date = new Date().getTime();
    img.src = "identcode?" + date;
}
  • effect

Here Insert Picture Description
Here Insert Picture Description

Source Project

https://github.com/xiaochen0517/StudySpace/tree/master/idea/TestDemo3

Published 50 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_25884515/article/details/103885865