验证码-图形验证码工具类

记录,备用

 /**
     * 已有验证码,生成验证码图片
     *
     * @param textCode       文本验证码
     * @param width          图片宽度
     * @param height         图片高度
     * @param interLine      图片中干扰线的条数
     * @param randomLocation 每个字符的高低位置是否随机
     * @param backColor      图片颜色,若为null,则采用随机颜色
     * @param foreColor      字体颜色,若为null,则采用随机颜色
     * @param lineColor      干扰线颜色,若为null,则采用随机颜色
     * @return 图片缓存对象
     */
    public static BufferedImage getImageCode(String textCode, int width, int height, int interLine,
                                                  boolean randomLocation, Color backColor, Color foreColor, Color lineColor) {

		Random r = new Random();
        BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = bim.getGraphics();

        // 画背景图
        g.setColor(backColor == null ? getRandomColor() : backColor);
        g.fillRect(0, 0, width, height);

        // 画干扰线
        //Random r = new Random();
        if (interLine > 0) {

            int x = 0, y = 0, x1 = width, y1 = 0;
            for (int i = 0; i < interLine; i++) {
                g.setColor(lineColor == null ? getRandomColor() : lineColor);
                y = r.nextInt(height);
                y1 = r.nextInt(height);

                g.drawLine(x, y, x1, y1);
            }
        }

        // 添加噪点
        float yawpRate = 0.01f;
        int area = (int) (yawpRate * width * height);
        for (int i = 0; i < area; i++) {
            int x = r.nextInt(width);
            int y = r.nextInt(height);
            bim.setRGB(x, y, r.nextInt(255));
        }

        // 写验证码

        // 字体大小为图片高度的80%
        int fCount = textCode.length();
        int fsize = (int) (height * 0.7);
        int fx = width / fCount;
        int fy = fsize;

        Font font = new Font("Fixedsys", Font.BOLD, fsize);
        g.setFont(font);

        // 写验证码字符
        for (int i = 0; i < fCount; i++) {
            // 每个字符高低是否随机
            fy = randomLocation ? (int) ((Math.random() * 0.3 + 0.6) * height) : fy;
            g.setColor(foreColor == null ? getRandomColor() : foreColor);
            g.drawString(textCode.charAt(i) + "", fx * i + (0 < i && i < fCount ? 3 : 0), fy);
        }

        g.dispose();

        return bim;
    }

	/**
     * 产生随机颜色
     *
     * @return
     */
    private static Color getRandomColor() {
        //Random r = new Random();
        Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
        return c;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值