• javaWeb图片验证码代码


    1. [代码]初始粗糙代码 

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.Random;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.sun.image.codec.jpeg.*;
    /**
     * 验证码图片生成Servlet类,直接调用该Servlet即可使用
     * 取值的时候调用session.getAttribute("code")得到生成的值
     * @author <a href="mailto:weijunqiang2010@gmail.com">Ajunboys</a>
     *
     */
    @WebServlet("/safecode")
    public class SafeCodeImageServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
            Random random = new Random();
            
            if (fc > 255)
                fc = 255;
            
            if (fc < 0)
                fc = 0;
            
            if (bc > 255)
                bc = 255;
            
            if (bc < 0)
                bc = 0;
            
            int r = fc + random.nextInt(bc - fc);
            int g = fc + random.nextInt(bc - fc);
            int b = fc + random.nextInt(bc - fc);
            
            return new Color(r, g, b);
        }
    
        @Override
        protected void service(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            // 设置输出
            response.setContentType("image/jpeg");
            
            int width = 80;
            int height = 30;
            
            // 产生随机数
            Random r = new Random();
            // 把随机数绘制成图像
            
            BufferedImage imgbuf = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);// 产生缓冲图像,80宽30高
            
            Graphics2D g = imgbuf.createGraphics();// 取得缓冲的绘制环境
            
            // 开始绘制 
            g.setColor(getRandColor(200, 250));// 设定背景色
            g.fillRect(0, 0, width, height);// 矩形图
            
            // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
            g.setColor(getRandColor(160, 200));
            
            for (int i = 0; i < 155; i++) {
                int x = r.nextInt(width);
                int y = r.nextInt(height);
                int xl = r.nextInt(12);
                int yl = r.nextInt(12);
            
                g.drawLine(x, y, x + xl, y + yl);
            }
            
            g.setColor(getRandColor(120, 240));
            
            // 随机产生100个干扰点,使图像中的验证码不易被其他分析程序探测到
            for (int i = 0; i < 100; i++) {
                int x = r.nextInt(width);
                int y = r.nextInt(height);
                
                g.drawOval(x, y, 0, 0);
            }
        
            g.setFont(new Font("Times New Roman", Font.PLAIN, 26));
        
            String scode = "";
        
            for (int i = 0; i < 4; i++) {
    //            String rand = String.valueOf(r.nextInt(10));
                String rand = randomCode();
                
                scode += rand;
                
                g.setColor(new Color(20 + r.nextInt(110), 20 + r.nextInt(110),
                        20 + r.nextInt(110)));
                
                // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
                g.drawString(rand+" ", (0==i) ? 12 : (12 * (i+1)+5), 23);
            }
            
            request.getSession().setAttribute("safecode", scode);
    
            // 输出图像
            ServletOutputStream out = response.getOutputStream();// 得到HTTP的流
            
            // JPEGCodec.createJPEGEncoder(out);转码
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);// 产生JPEG的图像加码器
            
            encoder.encode(imgbuf);
            out.flush();
        }
        
        private static String randomCode(){
            char[] dictionary = {
                    '2','3','4','5','6','7','8','9'
                    ,'a','b','c','d','e','f','g','h','i','j'
                    ,'k','m','n','p','q','r','s','t'
                    ,'u','v','w','x','y','z'
                    ,'A','B','C','D','E','F','G','H','J'
                    ,'K','L','M','N','P','Q','R','S','T'
                    ,'U','V','W','X','Y','Z'
                    /*'1','l','0','O','o','#','@','$','%','&','(',')','|','/','*'//暂时不用特殊字符(包括:数字1,0;字母:l,o,O)
                    ,'^','!','~','\'*/
                    };
            StringBuffer code = new StringBuffer();
            
            Random r = new Random();
            
            code.append(dictionary[r.nextInt(dictionary.length)]);
            
            return code.toString();
        }
    
    }
    View Code

    2. [代码]优化后的全代码

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.Random;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.annotation.WebServlet;
    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;
    
    /**
     * 验证码图片生成Servlet类,直接调用该Servlet即可使用
     * 取值的时候调用session.getAttribute("code")得到生成的值
     * @author <a href="mailto:weijunqiang2010@gmail.com">Ajunboys</a>
     *
     */
    @WebServlet("/safecode")
    public class SafeCodeImageServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
       
        static final char[] dictionary = {
                '2','3','4','5','6','7','8','9'
                ,'a','b','c','d','e','f','g','h','i','j'
                ,'k','m','n','p','q','r','s','t'
                ,'u','v','w','x','y','z'
                ,'A','B','C','D','E','F','G','H','J'
                ,'K','L','M','N','P','Q','R','S','T'
                ,'U','V','W','X','Y','Z'
                /*'1','l','0','O','o','#','@','$','%','&','(',')','|','/','*'//暂时不用特殊字符(包括:数字1,0;字母:l,o,O)
                ,'^','!','~','\'*/
                };
        static Random random = new Random();
        
        /**
         * 产生n[4,4+]个随机数
         * @param n
         * @return
         */
        static String getRandomString(int n){
            StringBuffer buffer = new StringBuffer();
            if (n < 4) {
                n = 4;
            }
            for (int i = 0; i < n; i++) {
                buffer.append(dictionary[random.nextInt(dictionary.length)]);
            }
            return buffer.toString();
        }
        
        /**
         * 随机颜色
         * @return
         */
        static Color getRandomColor(){
            return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
        }
        
        /**
         * 颜色反色
         * @param c
         * @return
         */
        static Color getReverseColor(Color c){
            return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());
        }
        
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("image/jpeg");
            
            String randomString = getRandomString(6);
            
            request.getSession(true).setAttribute("code", 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);
            
            //绘制最多100个噪音点
            for (int i = 0, n = random.nextInt(100); i < n; i++) {
                g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
            }
            
            ServletOutputStream out = response.getOutputStream();
            
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            
            encoder.encode(bi);
            
            out.flush();
            
            out.close();
        }
    
    }
    View Code
  • 相关阅读:
    Sql之表的连接总结
    sql之独立子查询和相关子查询总结
    canvas 绘点图
    gulp插件
    jquery插件开发模板
    js中substring和substr的用法比较
    phpStudy 2016 更新下载,新版支持php7.0
    phpStudy for Linux (lnmp+lamp一键安装包)
    用 Function.apply() 的参数数组化来提高 JavaScript程序性能
    Js apply() call()使用详解
  • 原文地址:https://www.cnblogs.com/zhang-cb/p/6112671.html
Copyright © 2020-2023  润新知