java generates image verification code

import javax.imageio.ImageIO;  
import java.awt.*;  
import java.awt.image.BufferedImage;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.util.Date;  
import java.util.Random;  
  
/**
 * Verification code generator
 *
 * @author  
 */  
public class ValidateCode {  
    // The width of the image.  
    private int width = 160;  
    // The height of the image.  
    private int height = 40;  
    // number of verification code characters  
    private int codeCount = 5;  
    // Number of verification code interference lines  
    private int lineCount = 150;  
    // verification code  
    private String code = null;  
    // verification code image Buffer  
    private BufferedImage buffImg = null;  
  
    // Verification code range, remove 0 (number) and O (pinyin) which are easy to confuse (lowercase 1 and L can also be removed, uppercase is not used)  
    private char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',  
            'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',  
            'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9'};  
  
    /**
     * Default constructor, set default parameters
     */  
    public ValidateCode() {  
        this.createCode();  
    }  
  
    /**
     * @param width image width
     * @param height image height
     */  
    public ValidateCode(int width, int height) {  
        this.width = width;  
        this.height = height;  
        this.createCode();  
    }  
  
    /**
     * @param width image width
     * @param height image height
     * @param codeCount number of characters
     * @param lineCount number of interference lines
     */  
    public ValidateCode(int width, int height, int codeCount, int lineCount) {  
        this.width = width;  
        this.height = height;  
        this.codeCount = codeCount;  
        this.lineCount = lineCount;  
        this.createCode();  
    }  
  
    public void createCode() {  
        int x = 0, fontHeight = 0, codeY = 0;  
        int red = 0, green = 0, blue = 0;  
  
        x = width / (codeCount + 2);//The width of each character (one character is left on the left and right)  
        fontHeight = height - 2;//The height of the font  
        codeY = height - 4;  
  
        // image buffer  
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
        Graphics2D g = buffImg.createGraphics();  
        // generate random numbers  
        Random random = new Random();  
        // fill the image with white  
        g.setColor(Color.WHITE);  
        g.fillRect(0, 0, width, height);  
        // Create font, can be modified to other  
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);  
//        Font font = new Font("Times New Roman", Font.ROMAN_BASELINE, fontHeight);  
        g.setFont(font);  
  
        for (int i = 0; i < lineCount; i++) {  
            // set random start and end coordinates  
            int xs = random.nextInt(width);//start of x coordinate  
            int ys = random.nextInt(height);//The start of the y coordinate  
            int xe = xs + random.nextInt(width / 8);//End of x coordinate  
            int ye = ys + random.nextInt(height / 8);//The end of the y coordinate  
  
            // Generate random color values, so that the color value of each output interference line will be different.  
            red = random.nextInt(255);  
            green = random.nextInt(255);  
            blue = random.nextInt(255);  
            g.setColor(new Color(red, green, blue));  
            g.drawLine(xs, ys, xe, ye);  
        }  
  
        // randomCode records the randomly generated verification code  
        StringBuffer randomCode = new StringBuffer();  
        // Randomly generate a verification code of codeCount characters.  
        for (int i = 0; i < codeCount; i++) {  
            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);  
            // Generate random color values, so that the color value of each character output will be different.  
            red = random.nextInt(255);  
            green = random.nextInt(255);  
            blue = random.nextInt(255);  
            g.setColor(new Color(red, green, blue));  
            g.drawString(strRand, (i + 1) * x, codeY);  
            // Combine the four random numbers generated.  
            randomCode.append(strRand);  
        }  
        // Save the four-digit verification code to the Session.  
        code = randomCode.toString();  
    }  
  
    public void write(String path) throws IOException {  
        OutputStream sos = new FileOutputStream(path);  
        this.write(sos);  
    }  
  
    public void write(OutputStream sos) throws IOException {  
        ImageIO.write(buffImg, "png", sos);  
        sos.close();  
    }  
  
    public BufferedImage getBuffImg() {  
        return buffImg;  
    }  
  
    public String getCode() {  
        return code;  
    }  
  
    /**
     * Test function, generated to d disk by default
     * @param args
     */  
    public static void main(String[] args) {  
        ValidateCode vCode = new ValidateCode(160,40,5,150);  
        try {  
            String path="D:/"+new Date().getTime()+".png";  
            System.out.println(vCode.getCode()+" >"+path);  
            vCode.write(path);  
        } catch (IOException e) {  
            e.printStackTrace ();  
        }  
    }  
}  

 

The following is the page call verification code

 

<div class="form-group  col-lg-6">  
    <label for="id" class="col-sm-4 control-label">  
        Verification code:  
    </label>  
    <div class="col-sm-8">  
        <input type="text" id="code" name="code" class="form-control" style="width:250px;"/>  
        <img id="imgObj" alt="验证码" src="/article/validateCode" onclick="changeImg()"/>  
        <a href="#" onclick="changeImg()">换一张</a>  
    </div>  
</div>  
  
<script type="text/javascript">  
    // refresh image  
    function changeImg() {  
        var imgSrc = $("#imgObj");  
        var src = imgSrc.attr("src");  
        imgSrc.attr("src", changeUrl(src));  
    }  
    //In order to make the image generated each time inconsistent, that is, to prevent the browser from reading the cache, it is necessary to add a timestamp  
    function changeUrl(url) {  
        var timestamp = (new Date()).valueOf();  
        var index = url.indexOf("?",url);  
        if (index > 0) {  
            url = url.substring(0, url.indexOf(url, "?"));  
        }  
        if ((url.indexOf("&") >= 0)) {  
            url = url + "×tamp=" + timestamp;  
        } else {  
            url = url + "?timestamp=" + timestamp;  
        }  
        return url;  
    }  
</script>  

 

The following is the output verification code of the controller layer

/**
 * Response verification code page
 * @return
 */  
@RequestMapping(value="/validateCode")  
public String validateCode(HttpServletRequest request,HttpServletResponse response) throws Exception{  
    // Set the type format of the response to image format  
    response.setContentType("image/jpeg");  
    // Disable image caching.  
    response.setHeader("Pragma", "no-cache");  
    response.setHeader("Cache-Control", "no-cache");  
    response.setDateHeader("Expires", 0);  
  
    HttpSession session = request.getSession();  
  
    ValidateCode vCode = new ValidateCode(120,40,5,100);  
    session.setAttribute("code", vCode.getCode());  
    vCode.write(response.getOutputStream());  
    return null;  
}  

 

The following is the controller layer to verify whether the verification code input is correct

String code = request.getParameter("code");  
HttpSession session = request.getSession();  
String sessionCode = (String) session.getAttribute("code");  
if (!StringUtils.equalsIgnoreCase(code, sessionCode)) { //Ignore the case of the verification code  
    throw new RuntimeException("The verification code does not correspond to code=" + code + " sessionCode=" + sessionCode);  
}  

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326694003&siteId=291194637