Tool class for generating image verification code
package com.zkingcai.scf.core.utils; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.util.Random; import javax.imageio.ImageIO; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * *************************************************************************** *Created: March 27, 2018 * Implemented function: picture verification code *Author: micha *Version: v0.0.1 ----------------------------------------------------------------------------- *Modification record: *Date version modified by modified content *March 27, 2018 v0.0.1 micha created **************************************************************************** */ public class ImgCaptchaUtil { private static Logger logger = LogManager.getLogger(ImgCaptchaUtil.class); // randomly generated string private static final String RANDOM_STRS = "23456789ABCDEFGHJKMNPRSTUXYZ"; private static final String FONT_NAME = "Fixedsys"; private static final int FONT_SIZE = 24; private Random random = new Random(); private int width = 110;// picture width private int height = 35;// Picture height private int lineNum = 50;// number of interference lines private int strNum = 4;// Randomly generate the number of characters /** * Generate random pictures */ public BufferedImage genRandomCodeImage(StringBuffer randomCode) { // The BufferedImage class is an Image class with a buffer BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); // Get the Graphics object, which is convenient for various drawing operations on the image Graphics g = image.getGraphics(); // set background color g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // set the color of the interference line g.setColor(getRandColor(110, 120)); // draw interference lines for (int i = 0; i <= lineNum; i++) { drowLine(g); } // draw random characters g.setFont(new Font(FONT_NAME, Font.ROMAN_BASELINE, FONT_SIZE)); for (int i = 1; i <= strNum; i++) { randomCode.append(drowString(g, i)); } g.dispose(); return image; } /** * Get a random color for a given range */ private Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * draw the string */ private String drowString(Graphics g, int i) { g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121))); String rand = String.valueOf(getRandomString(random.nextInt(RANDOM_STRS.length()))); g.translate(random.nextInt(3), random.nextInt(3)); int fsize = (int) (height * 0.7); int fy = fsize; g.drawString(rand, 18 * i, fy); return rand; } /** * Draw interference lines */ private void drowLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int x0 = random.nextInt(16); int y0 = random.nextInt(16); g.drawLine(x, y, x + x0, y + y0); } /** * Get random characters */ private String getRandomString(int num) { return String.valueOf(RANDOM_STRS.charAt(num)); } public static void main(String[] args) { ImgCaptchaUtil tool = new ImgCaptchaUtil(); StringBuffer code = new StringBuffer(); BufferedImage image = tool.genRandomCodeImage(code); logger.debug(">>> random code =: " + code); try { // Output the image in memory to the client through streaming ImageIO.write(image, "JPEG", new FileOutputStream(new File("random-code.jpg"))); } catch (Exception e) { // Record the underlying exception information logger.error(Exceptions.getErrorMessageWithNestedException(e)); } } }
Call the tool class, generate the image verification code, put the random verification code into the session, and write the image to the page
/** * ==================================================================== *Function: Get the verification code image and text (the verification code text will be saved in HttpSession) ---------------------------------------------------------------------- *Modification record: *Date version modified by modified content *March 27, 2018 v0.0.1 micha created ==================================================================== */ @RequestMapping("/getVerifyCodeImage") public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException { // Set the page to not be cached response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ImgCaptchaUtil tool = new ImgCaptchaUtil(); StringBuffer code = new StringBuffer(); BufferedImage image = tool.genRandomCodeImage(code); request.getSession().setAttribute("captcha", code.toString() + "|" + System.currentTimeMillis()); logger.debug("The verification code generated this time is [" + code.toString() + "], which has been stored in HttpSession"); // write to the browser ImageIO.write(image, "JPEG", response.getOutputStream()); }
Effect