Verification code image generation steps
Create a BufferedImage object.
Get the brush of the BufferedImage, that is, call the getGraphics() method to get the Graphics object.
Call the setColor() method and fillRect() method of the Graphics object to set the background color of the image.
Call the setColor() method and drawLine() method of the Graphics object to set the image interference line.
Call the setRGB() method of the BufferedImaged object to set the noise of the image.
Call the setColor() method, setFont() method and drawString() method of the Graphics object to set the image verification code.
Because the width and height of the image of the verification code must be determined according to the style of the website, the size of the font needs to be determined according to the width and height of the image, and a small skill is used.
package util;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;public class Verification { private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; /** * Generate an image with width as width, height as height, and verification code as code* @param width The width of the image* @param height The height of the image* @param code Verification code string* @return Return image verification code*/ public static BufferedImage getImage(int width, int height, String code){ return getImage(width, height, code, 20); } /** * Generate a width as width, height as height, The verification code is a code, the number of interference lines in the picture is lineCnt * @param width The width of the picture * @param height The height of the picture * @param code Verification code string * @param lineCnt The number of interference lines, it is recommended to be about 10, and it can be adjusted appropriately according to the result* @return Return the image verification code*/ public static BufferedImage getImage(int width, int height, String code, int lineCnt){ return createImage(width, height, code, lineCnt, 0.01); } /** * Generate a picture with width, height, height, and verification code is code, the number of interference lines in the picture is lineCnt * The noise ratio is noiseRate, that is, the percentage of noise pixels in the picture* @param width The width of the picture* @param height The height of the picture* @param code Verification code string* @param lineCnt The number of interference lines is recommended to be about 10, and you can adjust it appropriately according to the results* @param noiseRate The percentage of noise pixels in the picture to the total pixels* @return Return the image verification code*/ public static BufferedImage getImage(int width, int height, String code, int lineCnt, double noiseRate){ return createImage(width, height, code, lineCnt, noiseRate); } /** * * Generate an image with width, height, and verification code. The number of interference lines in the image is lineCnt * The noise ratio is noiseRate, that is, the percentage of noise pixels in the image* @param width The width of the image* @param height The height of the image* @param code Verification code string* @param lineCnt The number of interference lines is recommended to be about 10, and can be adjusted appropriately according to the results* @param noiseRate The percentage of noise pixels in the image to total pixels* @return Return the image verification code*/ private static BufferedImage createImage(int width, int height, String code, int lineCnt, double noiseRate){ int fontWidth = ((int)(width * 0.8)) / code.length(); int fontHeight = (int)(height * 0.7); //In order to generate good verification codes under any width and height, //The size of the fontWdith is the smaller in fontHeight, int fontSize = Math.min(fontWidth, fontHeight); //Int paddingX = (int) (width * 0.1); int paddingY = height - (height - fontSize) / 2; //Create an image BufferedImage buffimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //Get brush Graphics g = buffimg.getGraphics(); //Set the color of the brush g.setColor(getRandColor(200, 255)); //Then fill a rectangle, that is, set the background color g.fillRect(0, 0, width, height); //Set the interference line for (int i = 0; i < lineCnt; i++) { //Store to get the start and end points of the interference line int xs = (int)(Math.random() * width); int ys = (int)(Math.random() * height); int xe = (int)(Math.random() * width); int ye = (int)(Math.random() * height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // Add noise int area = (int) (noiseRate * width * height); for(int i=0; i<area; ++i){ int x = (int)(Math.random() * width); int y = (int)(Math.random() * height); buffimg.setRGB(x, y, (int)(Math.random() * 255)); } //Set font Font font = new Font("Ravie", Font.PLAIN, fontSize); g.setFont(font); for(int i=0; i<code.length(); ++i){ String ch = code.substring(i, i+1); g.setColor(getRandColor(1, 199)); g.drawString(ch, paddingX + fontWidth * i, paddingY); } return buffimg; } /** * Get the random color, the values of r,g,b are between L and R* @param L Left interval* @param R Right interval* @return Return the random color value*/ private static Color getRandColor(int L, int R){ if(L > 255) L = 255; if(R > 255) R = 255; if(L < 0) L = 0; if(R < 0) R = 0; int interval = R - L; int r = L + (int)(Math.random() * interval); int g = L + (int)(Math.random() * interval); int b = L + (int)(Math.random() * interval); return new Color(r, g, b); } /** * Randomly generate several strings composed of uppercase and lowercase letters and numbers* @param len Randomly generates len characters* @return Returns a randomly generated string consisting of uppercase and lowercase letters and numbers*/ public static String getRandCode(int len){ String code = ""; for(int i=0; i<len; ++i){ int index = (int)(Math.random() * ALPHABET.length()); code = code + ALPHABET.charAt(index); } return code; } /** * Convert the image to byte array* @param image Image* @return Return the byte array* @throws IOException */ public static byte[] getByteArray(BufferedImage image) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); return baos.toByteArray(); //ByteArrayOutputStream does not require close }}Use verification code picture
In the verificationCode.java servlet, call the above class to generate the verification code picture, and then return the picture to the client.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); // Randomly generate a string and write session String code = Verification.getRandCode(4); session.setAttribute("verification", code); BufferedImage image = util.Verification.getImage(100,30, code, 5); response.setContentType("image/png"); OutputStream out = response.getOutputStream(); out.write(util.Verification.getByteArray(image)); out.flush(); out.close(); }Set the verification code in index.jsp. When the user clicks the verification code, he calls the js code to request the server to obtain the new verification code. Because the above servlet that generates the verification code will be cached by the browser, the js code needs to give the servlet a random parameter, so that the browser will send a request to the server to get a new verification code, rather than reading it in the cache.
<%@page import="util.Verification"%><%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript"> function refreshcode(){ document.getElementById("verification").src= "/verificationCode/verificationCode?hehe="+Math.random(); } </script></head><body> <form action="<%=request.getContextPath()+"/checkVerification" %>" method="post"> Verification code:<input type="text" name="submitVerification"> <img id="verification" src="<%=request.getContextPath()+"/verificationCode" %>" onclick="refreshcode()"><br> <input type="submit" name="submit" value="submit"> </form> </body></html>Finally, in the checkVerification.java servlet, we determine whether the verification code entered by the user is correct. In order to facilitate users, the verification code is generally set to be case-insensitive, so it must be converted into lowercase letters before comparison.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); String verification = (String)session.getAttribute("verification"); String submitVerification = request.getParameter("submitVerification"); PrintWriter out = response.getWriter(); if(verification!=null && submitVerification!=null){ if(verification.toLowerCase().equals(submitVerification.toLowerCase())){ out.println("yes!!!"); } else{ out.println("no!!!"); } } else{ out.println("no!!!"); } session.removeAttribute("verification");//Prevent users from submitting forms repeatedly} /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }The final running rendering is as follows
The above is all about this article, I hope it will be helpful to everyone's learning.