zoukankan      html  css  js  c++  java
  • 简单的图形验证码

    我用例子解释吧:

    先来一个在Servlet中编写验证码的例子:

    package com.servlet.checkImage;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Random;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    
    public class checkImageDemo extends HttpServlet {
        public static final char[] CHARS={'2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'};
        public static Random random=new Random();
        
        public static String getRandomString(){
            StringBuffer buffer=new StringBuffer();
            for(int i=0;i<6;i++){
                buffer.append(CHARS[random.nextInt(CHARS.length)]);
            }
            return buffer.toString();
        }
    
        public static Color getRandomColor(){
            return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
        }
        
        public static Color getReverseColor(Color c){//返回某颜色的反色
            return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
        }
        
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("image/jpeg");//设置输出类型,必须的
            
            String randomString=getRandomString();
            request.getSession(true).setAttribute("randomString", randomString);
            
            int width=100;
            int height=30;
            
            Color color=getRandomColor();//用于背景颜色
            Color reverse=getReverseColor(color);//用于前景颜色
            
            BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//创建一个彩色图片
            Graphics2D g=bi.createGraphics();//获取绘图对象
            g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));//设置字体
            g.setColor(color);
            g.fillRect(0, 0, width, height);//绘制背景
            g.setColor(reverse);
            g.drawString(randomString, 18, 20);
            for(int i=0,n=random.nextInt(100);i<n;i++){
                //最多画100个噪音点
                g.drawRect(random.nextInt(width),random.nextInt(height), 1, 1);//随机噪音点
            }
            ServletOutputStream out=response.getOutputStream();//转化为JPEG格式
            JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);//编码器
            encoder.encode(bi);//对图片进行编码
            out.flush();//输出到客户端
            
        }
    
        
        public void doPost(HttpServletRequest request, HttpServletResponse response){
        
        }
    
        
    }
    View Code

    再来一个在类中编写验证码的例子:

    package com.servlet.checkImage;
    
    import java.awt.Color;
    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 Image1 {
        public Random random=new Random();
        
        public String[] getRandomString(){
            String validateCode[]=new String[4];
            for(int i=0;i<4;i++){
                validateCode[i]=random.nextInt(10)+"";
            }        
            return validateCode;
        }
        
        public Color getRandomColor(){
            Color color=new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
            return color;
        }
        
        public Color getResverseColor(Color color){
            Color reverse=new Color(255-color.getRed(),255-color.getGreen(),255-color.getBlue());//获取该颜色的反色,如果需要噪点或者切割线可以使用这个
            return reverse;
        }
        
        public String getImage(OutputStream os){
            int width=80;
            int height=25;
            
            BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
            Graphics g=bi.getGraphics();//获得一个画笔
            //g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,16));//设置字体
            
            //边框
            g.setColor(Color.black);
            g.drawRect(0, 0, width-1, height-1);
            
            Color back=getRandomColor();
            g.setColor(back);
            g.fillRect(0, 0, width, height);//填充背景
                        
            String[] code=getRandomString();
            for(int i=0;i<code.length;i++){
                g.setColor(getRandomColor());
                g.drawString(code[i], 5+(i+1)*15, 15);
            }
            
            Color reserse=getResverseColor(back);
            g.setColor(reserse);
            g.drawLine(0, random.nextInt(height), width, random.nextInt(height));//干扰线
            g.drawLine(random.nextInt(width), 0,height, random.nextInt(width));
    
            g.dispose();//释放图文上下文
            
            try {
                ImageIO.write(bi, "JPEG", os);
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
            
            return new String(code.toString());
            
        }
    
    }
    View Code

    在类中编写的验证码调用需要一个jsp作为中间介质:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%@page contentType="image/jpeg" %>
    
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'tempImage.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
         <jsp:useBean id="image" scope="page" class="com.servlet.checkImage.Image1"></jsp:useBean>
         <%
            String str=image.getImage(response.getOutputStream());
            session.setAttribute("checkCode",str);
            
            out.clear();
            out=pageContext.pushBody();
         %>
        
      </body>
    </html>
    View Code

    在Servlet中的验证码可以直接调用:

    两个的调用示例在这个例子里面:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'checkImg.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body>
        <script>
          function reloadImage(m){
          if(m==0){
            document.getElementById('btn').disabled=true;
            document.getElementById('identity').src='checkImageDemo?ts='+new Date().getTime();
          }
          if(m==1){
            document.getElementById('btn1').disabled=true;
            document.getElementById('identity1').src='tempImage.jsp?ts='+new Date().getTime();
          }
          }
          
        </script>
        <img src="checkImageDemo" id="identity" onload="btn.disabled=false;" />
        <input type="button" value="换个图片" onclick="reloadImage(0)" id="btn"/>
        <br/>
        <img src="tempImage.jsp" id="identity1" onload="btn1.disabled=false;" />
        <input type="button" value="换个图片" onclick="reloadImage(1)" id="btn1"/>
      </body>
    </html>
    View Code

    至于一些配置的就不啰嗦了。认真看看代码就基本验证码该会制作了。

  • 相关阅读:
    WPF 使用 Direct2D1 画图 绘制基本图形
    WPF 使用 Direct2D1 画图 绘制基本图形
    dot net core 使用 IPC 进程通信
    dot net core 使用 IPC 进程通信
    win2d 图片水印
    win2d 图片水印
    Java实现 LeetCode 240 搜索二维矩阵 II(二)
    PHP closedir() 函数
    PHP chroot() 函数
    PHP chdir() 函数
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5129695.html
Copyright © 2011-2022 走看看