This example shares the specific code of Java implementation login verification code for your reference. The specific content is as follows
1. ValidateCode.java
import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.io.OutputStream;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.ServletException;import org.springframework.stereotype.Service;/** * Login verification code* */public class ValidateCode { /** * Get the verification code image* @param out * @param number Verify the number* @throws ServletException * @throws IOException */ public void getImage(OutputStream out,String number) throws ServletException, IOException { //0. Create a blank image BufferedImage image=new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB); //1. Get the image brush Graphics g = image.getGraphics(); Random r=new Random(); //2. Set the brush color (nextInt(n) in the Random class returns a random number greater than or equal to 0 and less than n) g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255))); //3. Draw the background of the rectangle g.fillRect(0, 0, 100, 30); //4. Call a custom method to get the string of alphanumeric combinations of length 4 g.setColor(new Color(0,0,0)); g.setFont(new Font(null,Font.BOLD,24)); //5. After setting the color font, draw the string (x/y, the position of the leftmost character) g.drawString(number, 20, 24); //6. Draw 8 interference lines (alpha means transparency) for(int i=0;i<8;i++){ g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(255))); g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30)); } ImageIO.write(image, "jpeg", out); } //Custom method to get the string of alphanumeric combinations of length size public String getNumber(int size){ String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String number=""; Random r = new Random(); for(int i=0;i<size;i++){ number+=str.charAt(r.nextInt(str.length())); } return number; }}2. Controller
@RequestMapping(value = "/check",method={RequestMethod.GET}) @ResponseBody public void check(HttpServletRequest req) { try { HttpServletResponse response = this.getResponse(); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=" + "vcode.jpeg"); String number = validateCode.getNumber(4); validateCode.getImage(response.getOutputStream(),number); } catch (Exception e) { } }3. html
<img src="http://127.0.0.1:8080/test/check">
Reproduction diagram
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.