生成图片验证码

  下面给大家介绍一些生成图片验证码的工具方法:

  一、生成随机字符串

  

public static void main(String args[]) {
        //产生随机字符串
        System.out.println(TestImage.getCharArray(4));
    }

    private static final char[] randChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'P', 'Q', 'M', 'N', 'Y', 'W' };

    /**
     * 产生随机字符串
     *
     * @param charSize
     * @return
     */
    public static char[] getCharArray(int charSize) {
        char[] chars = new char[charSize];
        Random ran = new Random();
        for (int i = 0; i < charSize; i++) {
            chars[i] = randChars[ran.nextInt(randChars.length)];
        }
        return chars;
    }

   二、生成一张空白的图片

  

public static void main(String args[]) {
        BufferedImage img = createBlankVerifImage(4);
        File outputfile  = new File("D:/blank.png");
        try {
            ImageIO.write(img, "png", outputfile);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 产生一张空白的图片验证码
     *
     * @param charCount 字符数
     * @return
     */
    public static BufferedImage createBlankVerifImage(int charCount) {
        return createBlankVerifImage(20 * charCount, 40);
    }

    /**
     * 产生一张空白的图片验证码
     *
     * @param width 图片宽度
     * @param height 图片高度
     * @return
     */
    public static BufferedImage createBlankVerifImage(int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphic = image.getGraphics();
        graphic.setColor(new Color(231, 231, 231));// Color.LIGHT_GRAY
        graphic.fillRect(0, 0, width, height);
        return image;
    }

  三、生成有验证码的图片

  

public static void main(String args[]) {
        char[] chars = ImageTool.getCharArray(4);
        BufferedImage img = ImageTool.createRandVerifImage(chars);;
        File outputfile  = new File("D:/save.png");
        try {
            ImageIO.write(img, "png", outputfile);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final char[] randChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'P', 'Q', 'M', 'N', 'Y', 'W' };

    /**
     * 产生随机字符串
     *
     * @param charSize
     * @return
     */
    public static char[] getCharArray(int charSize) {
        char[] chars = new char[charSize];
        Random ran = new Random();
        for (int i = 0; i < charSize; i++) {
            chars[i] = randChars[ran.nextInt(randChars.length)];
        }
        return chars;
    }

    /**
     * 产生一张图片验证码
     *
     * @param chars 字符
     * @return
     */
    public static BufferedImage createRandVerifImage(char[] chars) {
        return createRandVerifImage(chars, 20 * chars.length, 40, 5, 30);
    }

    /**
     * 产生一张图片验证码
     *
     * @param chars 字符
     * @param width 图片宽度
     * @param height 图片高度
     * @param lineCount 干扰线数量
     * @param fontSize 字体大小
     * @return
     */
    public static BufferedImage createRandVerifImage(char[] chars, int width, int height, int lineCount, int fontSize) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphic = image.getGraphics();
        graphic.setColor(new Color(231, 231, 231));// Color.LIGHT_GRAY
        graphic.fillRect(0, 0, width, height);
        Random ran = new Random();
        // 画随机字符
        for (int i = 0; i < chars.length; i++) {
            graphic.setColor(new Color(ran.nextInt(156), ran.nextInt(156), ran.nextInt(156)));
            graphic.setFont(new Font(null, Font.BOLD + Font.ITALIC, fontSize));
            graphic.drawString(chars[i] + "", (i * width - 10) / chars.length, (height - fontSize) / 2 + fontSize - 5);
        }
        // 画干扰线
        for (int i = 0; i < lineCount; i++) {
            graphic.setColor(new Color(ran.nextInt(156), ran.nextInt(156), ran.nextInt(156)));
            graphic.drawLine(ran.nextInt(width), ran.nextInt(height), ran.nextInt(width), ran.nextInt(height));
        }
        return image;
    }

  四、生成电子签章

  

public static void main(String args[]) {

        try {
            BufferedImage img = TestImage.createSignImage("daishoucheng 代守诚");
            File outputfile  = new File("D:/save.png");
            ImageIO.write(img, "png", outputfile);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 产生电子签名图片
     * @param str
     * @return
     * @throws Exception
     */
    public static BufferedImage createSignImage(String str) throws Exception {

        Font font=new Font("华文行楷", Font.BOLD, 100);
        int can=font.canDisplayUpTo(str);
        if (can>=0){
            System.out.println("字符串【"+str+"】包含无法显示的文字,使用宋体");
            font=new Font("宋体", Font.BOLD, 100);
            can=font.canDisplayUpTo(str);
            if (can>=0) {
                System.out.println("使用宋体后字符串【" + str + "】任然无法正常显示");
            }
        }
        return createTextImage(str,font,Color.BLACK,str.length()*127,str.length()*127);
    }

    /**
     * 生成无背景的文字图片
     * @param str 文字
     * @param font 文字字体
     * @param color 文字颜色
     * @param width 图片宽度
     * @param height 图片高度
     * @return
     * @throws Exception
     */
    public static BufferedImage createTextImage(String str, Font font,Color color,Integer width, Integer height) throws Exception {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
//        g.setColor(Color.WHITE);
//        g.fillRect(0, 0, width, height);

        /** 增加下面的代码使得背景透明*/
        image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g.dispose();
        g = image.createGraphics();
        /** 背景透明代码结束*/
        g.setColor(color);
        g.setFont(font);
        /** 用于获得垂直居中y */
        g.setClip(0, 0, width, height);
        Rectangle clip = g.getClipBounds();
        FontMetrics fm = g.getFontMetrics(font);
        int ascent = fm.getAscent();
        int descent = fm.getDescent();
        int y = (clip.height - (ascent + descent)) / 2 + ascent;
        /** 用于获得水平居中x */
        int textWidth=fm.stringWidth(str);
        int x = (clip.width - textWidth )/ 2;
        g.drawString(str, x, y);// 画出字符串
        g.dispose();
        return image;
    }
原文地址:https://www.cnblogs.com/daishoucheng/p/10245861.html