JFinal 验证码绘制

来源:互联网 发布:compareto java用法 编辑:程序博客网 时间:2024/06/04 19:59

很丑的验证码


import com.jfinal.kit.HashKit;import com.jfinal.kit.LogKit;import com.jfinal.kit.StrKit;import javax.imageio.ImageIO;import javax.servlet.ServletOutputStream;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletResponse;import java.awt.*;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;/** * 移动端验证码 * Created by Admin on 2017/10/10. */public class MobileCaptcha {    // 默认的验证码大小    private static final int WIDTH = 108, HEIGHT = 40;    private static String captchaName = "mycaptcha";    //随机的数字    private static final String[] strArr = {            "3", "4", "5", "6", "7", "8", "9",            "A", "B", "C", "D", "E", "F", "G", "H",            "J", "K", "M", "N", "P", "Q", "R", "S",            "T", "U", "V", "W", "X", "Y"    };    /**     * 设置 captchaName     */    public static void setCaptchaName(String captchaName) {        if (StrKit.isBlank(captchaName)) {            throw new IllegalArgumentException("captchaName can not be blank.");        }        MobileCaptcha.captchaName = captchaName;    }    //验证码字体(字体,风格,字号)    private static final Font[] RANDOM_FONT = new Font[]{        new Font("TimesRoman",Font.BOLD,38),        new Font("Arial",Font.BOLD,36),        new Font("Bell MT",Font.BOLD,32),        new Font("nyala",Font.BOLD,34),        new Font("Monospaced",Font.BOLD,36)    };    /**     * 生成验证码     */    public static void render(HttpServletResponse response){        //生成一个画布        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);        //画验证码,返回一个4位数字        String code = drawGraphic(image);        //转大写        code = code.toUpperCase();        //md5 code        code = HashKit.md5(code);        Cookie cookie = new Cookie("mycaptcha", code);        //有效时间 秒        cookie.setMaxAge(-1);        cookie.setPath("/");        try {            // try catch 用来兼容不支持 httpOnly 的 tomcat、jetty            cookie.setHttpOnly(true);        } catch (Exception e) {            e.printStackTrace();            LogKit.logNothing(e);        }        //设置响应,不缓存图片        response.addCookie(cookie);        response.setHeader("Pragma","no-cache");        response.setHeader("Cache-Control","no-cache");        response.setDateHeader("Expires", 0);        response.setContentType("image/jpeg");        //程序输出流        ServletOutputStream sos = null;        try {            //获取输出流            sos = response.getOutputStream();            //写入图片            ImageIO.write(image,"jpeg",sos);        } catch (IOException e) {            e.printStackTrace();        } finally {            if(sos != null){                try {                    //关流                    sos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    /**     * 画图     * @param image 画布     * @return 4位验证码数字     */    private static String drawGraphic(BufferedImage image){        //在画布上创建一个图像        Graphics2D g2 = image.createGraphics();        //插值提示键。interpolation 提示控制在图像呈现操作过程中如何过滤图像像素或重新对其取样。        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);        //图形抗锯齿        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);        //字体抗锯齿        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);        //设定边框颜色        //设定背景颜色        g2.setColor(getRandomColor(200,250));        g2.fillRect(0,0,WIDTH,HEIGHT);//x,y,长,宽        //随机一个字体        Random random = new Random();        int randomFontIndex = random.nextInt(RANDOM_FONT.length);//随机数组的长度中随机一个        Font font = RANDOM_FONT[randomFontIndex];        g2.setFont(font);        //背景中的鸭蛋        Color color;        for(int i = 0; i < 10 ; i++){            color = getRandomColor(120,200);            g2.setColor(color);            g2.drawOval(random.nextInt(WIDTH),random.nextInt(HEIGHT), 5+random.nextInt(10), 5+random.nextInt(10));//画椭圆鸭蛋 x,y,长,宽            color = null;        }                //随机产生4位验证码        String sRand = "";        for(int i = 0; i < 4; i++){            String randNum = strArr[random.nextInt(strArr.length)];//            String randNum = String.valueOf(strArr[random.nextInt(strArr.length)]);            sRand += randNum;            //旋转读书 最好小于45            int degree = random.nextInt(28);            //(4个数字)如果是偶数,右倾斜            if(i % 2 == 0){                degree = degree * (-1);            }            //定义坐标            int x = 22 * i, y = 21;            //旋转区域。将当前的 Graphics2D Transform 与平移后的旋转转换连接。            //旋转角度,x,y            g2.rotate(Math.toRadians(degree),x,y);            //字体颜色            color = getRandomColor(10,120);            g2.setColor(color);            //将验证码显示到图像中            g2.drawString(randNum, x + 8, y + 10);            //旋转之后,必须旋转回来            g2.rotate(-Math.toRadians(degree), x, y);            color = null;        }        //图片中的线        g2.setColor(getRandomColor(0,60));        //设置画笔,画笔的宽度为3        BasicStroke basicStroke = new BasicStroke(2);        g2.setStroke(basicStroke);        //画出曲线        //x1 - 起始点的 X 坐标    y1 - 起始点的 Y 坐标        //ctrlx - 控制点的 X 坐标 ctrly - 控制点的 Y 坐标        // x2 - 结束点的 X 坐标  y2 - 结束点的 Y 坐标//        QuadCurve2D.Double curve = new QuadCurve2D.Double(0d, random.nextInt(HEIGHT - 8) + 4, WIDTH / 2, HEIGHT / 2, WIDTH, random.nextInt(HEIGHT - 8) + 4);//        g2.draw(curve);        //绘制干扰线//        Random random = new Random();        g2.setColor(getRandomColor(160, 200));// 设置线条的颜色        for (int i = 0; i < 4; i++) {            int x = random.nextInt(WIDTH - 1);            int y = random.nextInt(HEIGHT - 1);            int xl = random.nextInt(6) + 1;            int yl = random.nextInt(12) + 1;            g2.drawLine(x, y, x + xl + 40, y + yl + 20);        }        //销毁图像        g2.dispose();        return sRand;    }    /**     * 给定范围获得随机颜色     * @param fc 前景色     * @param bc 背景色     * @return 颜色对象(r,g,b)     */    private static Color getRandomColor(int fc, int bc){        Random random = new Random();        if(fc > 255){            fc = 255;        }        if(bc >255){            bc = 255;        }        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);    }}




原创粉丝点击