Java generated image verification code sample program

  • 2020-04-01 02:31:41
  • OfStack


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> Landing page </title>
<script type="text/javascript">
 function refresh() {
  loginForm.image.src = "creatImage.jsp";
 }
</script>
</head>
<body>
<h1> Welcome to this system </h1><br>
<form action="" method = "post" name="loginForm">
 <label> account :<input name="username" type="text" /></label><br>
 <label> password :<input name="password" type="password" /></label><br>
 <label> Verification code :<input name="code" type="text" /></label>
 <!--  Treat the captcha as a picture  -->
    <img name="image" border="0" src="creatImage.jsp" onclick="refresh()" />
 <input type="submit" value=" landing " />
</form>
</body>
</html>


<%@page import="java.util.Random"%>
<%@page import="java.awt.Graphics"%>
<%@page import="javax.imageio.*"%>
<%@page import="java.awt.*"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
 final char[] str = {'0','1','2','3','4','5','6','7','8','9',
    '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','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'};
 int width=100,height=60;
 BufferedImage bi = new BufferedImage(width,height,
   BufferedImage.TYPE_INT_RGB);
 Graphics g = bi.getGraphics();
 g.setColor(new Color(200,200,200));
 g.fillRect(0, 0, width, height);
 Random rnd = new Random();
 StringBuffer sb = new StringBuffer("");
 //Produces a four-digit alphanumeric captcha with the color of each number
 for(int i=0; i<4; i++) {
  int num = rnd.nextInt(str.length);
  Color c = new Color(rnd.nextInt(256),
    rnd.nextInt(256),rnd.nextInt(256));
  g.setColor(c);
  g.setFont(new Font("", Font.BOLD+Font.ITALIC, 20));
  g.drawString(str[num]+"", 10, 17);
  sb.append(str[num]);
 }
 //Cross interference lines
 for(int i=0; i<10; i++) {
  Color c = new Color(rnd.nextInt(256),
    rnd.nextInt(256),rnd.nextInt(256));
  g.setColor(c);
  g.drawLine(rnd.nextInt(width), rnd.nextInt(height), 
    rnd.nextInt(width), rnd.nextInt(height));
 }
 String s = new String(sb);
 
 //Verification code stored in the session, convenient in the login check page comparison
 session.setAttribute("image",s);
 //Output to page
 ImageIO.write(bi,"JPEG",response.getOutputStream());
 
 out.clear();
 out = pageContext.pushBody();

%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> Images generated </title>
</head>
<body>
</body>
</html>


Related articles: