Java image verification code implementation code

  • 2020-04-01 01:57:22
  • OfStack


makeCertPic.java
  package pic;
  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;
  
  public class makeCertPic {
    //The character set that can appear in a captcha picture can be modified as needed
    private char mapTable[]={
       'a','b','c','d','e','f',
       'g','h','i','j','k','l',
       'm','n','o','p','q','r',
       's','t','u','v','w','x',
       'y','z','0','1','2','3',
       '4','5','6','7','8','9'};
    
   public String getCertPic(int width, int height, OutputStream os) {
   if(width<=0)width=60;
   if(height<=0)height=20; 
   BufferedImage image = new BufferedImage(width, height, 
      BufferedImage.TYPE_INT_RGB); 
   //Getting the graphics context
   Graphics g = image.getGraphics(); 
   //Setting the background color
   g.setColor(new Color(0xDCDCDC)); 
   g.fillRect(0, 0, width, height); 
   //Picture frame
   g.setColor(Color.black); 
   g.drawRect(0,0,width-1,height-1); 
   //Take the randomly generated authentication code
   String strEnsure = "";
   //4 represents a 4-bit verification code. If you want to generate more bits, increase the value
   for(int i=0; i<4; ++i) {
strEnsure+=mapTable[(int)(mapTable.length*Math.random())];
   }  
   //Displays the authentication code in the image, and adds a drawString statement if you want to generate more bits of authentication code
   g.setColor(Color.black); 
   g.setFont(new Font("Atlantic Inline",Font.PLAIN,18)); 
   String str = strEnsure.substring(0,1); 
   g.drawString(str,8,17); 
   str = strEnsure.substring(1,2); 
   g.drawString(str,20,15); 
   str = strEnsure.substring(2,3); 
   g.drawString(str,35,18);   
   str = strEnsure.substring(3,4); 
   g.drawString(str,45,15); 
   //I randomly generate 10 interference points
   Random rand = new Random();
   for (int i=0;i<10;i++) { 
    int x = rand.nextInt(width); 
    int y = rand.nextInt(height); 
    g.drawOval(x,y,1,1); 
   } 
   //Freeing the graph context
   g.dispose();   
   try {
    //Output the image to the page
    ImageIO.write(image, "JPEG", os);
   } catch (IOException e) {
    return "";
   }  
   return strEnsure;
   }
  }

In the getCertPic() method, an instance object of the memory image is first created, then the graphics context object of the memory image is obtained, and then the background and border are drawn with the context object. Next, randomly generate 4 characters in mapTable[] array, constitute a string as a verification string, and output in memory, in order to cause some interference, randomly draw 10 interference points, if you want to increase the effect of interference, you can draw more points.
The makecertpic.jsp page is used to call the javabeans that generate the captcha image and is displayed on the client side. The source code is as follows:
MakeCertPic. JSP


  <%@page contentType="image/jpeg" %>
  <jsp:useBean id="image" scope="page" class="pic.makeCertPic" />
  <%
  String str=image.getCertPic(0,0,response.getOutputStream());
     //Store the authentication code in SESSION
  session.setAttribute("certCode", str); 
  out.clear();
   out = pageContext.pushBody();
  %>

The generated verification code is written here as a session variable, so in the data page that receives input from the login page, the verification code entered by the user can be compared with this session variable, if the same means that the verification passed.
LoginPic. JSP


  <%@ page contentType="text/html;charset=GB2312" %>
<script type="text/javascript">
  function reloadcode(){
                var verify=document.getElementById('code');
                verify.setAttribute('src','makeCertPic.jsp?it='+Math.random());
        }
</script>
  <html>
   <head><title> The login page </title></head>
   <body>
     <table align="center" border="0">
   <tralign="center"><td><fontcolor="red"><html:errors/></font></td></tr>
   <tr align="center"><td> System login </td></tr>
   <form. action="loginCheck.jsp" method="post" focus="username">
   <tr><td> User name: <input type="text" name="username"/></td></tr>
     <tr><td> The secret    Code: <input type="password"name="password"/></td></tr>
   <tr><td> Verification code <img src="makeCertPic.jsp" id="code" onclick="reloadcode()" style="cursor: pointer;" alt=" Can't see clearly , In a "> </td></tr>
<tralign="left"><td>        
   <input type="submit" value=" determine "/></td></tr>
   </form>
   </table>
   </body>
  </html>

Whether the input of verification code is correct can be verified by the following statement:


  String certCode=request.getParameter("certCode");
  if(certCode.equals((String)session.getAttribute("certCode")))
   out.print(" Correct verification code input ");
  else
   out.print(" Error in captcha input ");


Related articles: