zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java生成图片验证码示例程序

JAVA程序 示例 图片 生成 验证码
2023-06-13 09:15:13 时间

复制代码代码如下:


<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
   pageEncoding="UTF-8"%>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>登陆页面</title>
<scripttype="text/javascript">
 functionrefresh(){
  loginForm.image.src="creatImage.jsp";
 }
</script>
</head>
<body>
<h1>欢迎登陆本系统</h1><br>
<formaction=""method="post"name="loginForm">
 <label>账号:<inputname="username"type="text"/></label><br>
 <label>密码:<inputname="password"type="password"/></label><br>
 <label>验证码:<inputname="code"type="text"/></label>
 <!--将验证码当做图片处理-->
   <imgname="image"border="0"src="creatImage.jsp"onclick="refresh()"/>
 <inputtype="submit"value="登陆"/>
</form>
</body>
</html>

复制代码代码如下:


<%@pageimport="java.util.Random"%>
<%@pageimport="java.awt.Graphics"%>
<%@pageimport="javax.imageio.*"%>
<%@pageimport="java.awt.*"%>
<%@pageimport="java.awt.image.BufferedImage"%>
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
   pageEncoding="UTF-8"%>
<%
 finalchar[]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"};
 intwidth=100,height=60;
 BufferedImagebi=newBufferedImage(width,height,
   BufferedImage.TYPE_INT_RGB);
 Graphicsg=bi.getGraphics();
 g.setColor(newColor(200,200,200));
 g.fillRect(0,0,width,height);
 Randomrnd=newRandom();
 StringBuffersb=newStringBuffer("");
 //产生四位数的字母数字验证码,各个数字的颜色也随即
 for(inti=0;i<4;i++){
  intnum=rnd.nextInt(str.length);
  Colorc=newColor(rnd.nextInt(256),
    rnd.nextInt(256),rnd.nextInt(256));
  g.setColor(c);
  g.setFont(newFont("",Font.BOLD+Font.ITALIC,20));
  g.drawString(str[num]+"",10,17);
  sb.append(str[num]);
 }
 //划干扰线
 for(inti=0;i<10;i++){
  Colorc=newColor(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));
 }
 Strings=newString(sb);
 /*
 若是产生四位数字,则nextInt(8999)+1000;
 然后String.valueOf转换为String
 */
 //验证码存入session里,方便在登陆校检页比对
 session.setAttribute("image",s);
 //输出到页面
 ImageIO.write(bi,"JPEG",response.getOutputStream());
 /*
 加入下面这两句什么作用呢?
 否则报异常:java.lang.IllegalStateException:getOutputStream()
 hasalreadybeencalledforthisresponse
 不管原因了
 */
 out.clear();
 out=pageContext.pushBody();

%>
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<title>图片生成</title>
</head>
<body>
</body>
</html>