图形验证码生成工具

一、引用所需的包

<dependencies>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi</artifactId>
            <version>3.0.0</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.7</version>
            <type>jar</type>
        </dependency>
 </dependencies>


二、工具类

public class CodeUtil {
   public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /** 
     * 使用系统默认字符源生成验证码 
     * @param verifySize    验证码长度 
     * @return 
     */  
    public static String generateVerifyCode(int verifySize){  
        return generateVerifyCode(verifySize, VERIFY_CODES);  
    }  
    /** 
     * 使用指定源生成验证码 
     * @param verifySize    验证码长度 
     * @param sources   验证码字符源 
     * @return 
     */  
    public static String generateVerifyCode(int verifySize, String sources){  
        if(sources == null || sources.length() == 0){  
            sources = VERIFY_CODES;  
        }  
        int codesLen = sources.length();  
        Random rand = new Random(System.currentTimeMillis());  
        StringBuilder verifyCode = new StringBuilder(verifySize);  
        for(int i = 0; i < verifySize; i++){  
            verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));  
        }  
        return verifyCode.toString();  
    }  
      
    /** 
     * 生成随机验证码文件,并返回验证码值 
     * @param w 
     * @param h 
     * @param outputFile 
     * @param verifySize 
     * @return 
     * @throws IOException 
     */  
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{  
        String verifyCode = generateVerifyCode(verifySize);  
        outputImage(w, h, outputFile, verifyCode);  
        return verifyCode;  
    }  
      
    /** 
     * 输出随机验证码图片流,并返回验证码值 
     * @param w 
     * @param h 
     * @param os 
     * @param verifySize 
     * @return 
     * @throws IOException 
     */  
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{  
        String verifyCode = generateVerifyCode(verifySize);  
        outputImage(w, h, os, verifyCode);  
        return verifyCode;  
    }  
      
    /** 
     * 生成指定验证码图像文件 
     * @param w 
     * @param h 
     * @param outputFile 
     * @param code 
     * @throws IOException 
     */  
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException{  
        if(outputFile == null){  
            return;  
        }  
        File dir = outputFile.getParentFile();  
        if(!dir.exists()){  
            dir.mkdirs();  
        }  
        try{  
            outputFile.createNewFile();  
            FileOutputStream fos = new FileOutputStream(outputFile);  
            outputImage(w, h, fos, code);  
            fos.close();  
        } catch(IOException e){  
            throw e;  
        }  
    }  
      
    /** 
     * 输出指定验证码图片流 
     * @param w 
     * @param h 
     * @param os 
     * @param code 
     * @throws IOException 
     */  
    public static void outputImage(int w,  
                            int h,  
                            OutputStream os,  
                            String code) throws IOException{  
        int verifySize = code.length();  
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);  
        Random rand = new Random();  
        Graphics2D g2 = image.createGraphics();  
        Color[] colors = new Color[5];  
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,  
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,  
                Color.PINK, Color.YELLOW };  
        float[] fractions = new float[colors.length];  
        for(int i = 0; i < colors.length; i++){  
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];  
            fractions[i] = rand.nextFloat();  
        }  
        Arrays.sort(fractions);  
        Paint linearPaint = new LinearGradientPaint(0, 0, w, h, fractions, colors);  
        Paint linearPaint2 = new LinearGradientPaint(0, 0, w, h, new float[]{0.3f, .6f, .8f, .9f}, new Color[]{Color.BLUE, Color.BLACK, Color.GREEN, Color.BLUE});  
        //设置图片背景为白色  
        g2.setPaint(Color.WHITE);  
        g2.fillRect(0, 0, w, h);  
        //设置图片渐变背景  
        g2.setPaint(linearPaint);  
        g2.fillRoundRect(0, 0, w, h, 5, 5);  
          
        g2.setPaint(linearPaint2);  
        int fontSize = (int) (Math.min(w/verifySize, h));  
        Font font = new Font("微软雅黑", Font.BOLD, fontSize);  
        g2.setFont(font);  
        char[] chars = code.toCharArray();  
        for(int i = 0; i < verifySize; i++){  
            AffineTransform affine = new AffineTransform();  
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);  
            g2.setTransform(affine);  
            g2.drawChars(chars, i, 1, (w / verifySize) * i, h/2 + fontSize /2);  
        }  
        g2.dispose();  
        ImageIO.write(image, "jpg", os);  
    }  
    
//    public static void main(String[] args) throws IOException{  
//        File dir = new File("F:/verifies");  
//        int w = 200, h = 80;  
//        for(int i = 0; i < 100; i++){  
//            String verifyCode = generateVerifyCode(4);  
//            File file = new File(dir, verifyCode + ".jpg");  
//            outputImage(w, h, file, verifyCode);  
//        }  
//    }  
}

三、调用

<div class="form-group">
                        <label for="verifyCode"><span class="form-require"></span>验证码:</label>
                        <div class="form-control-box">
                            <input class="form-control" type="text" id="verifyCode" value="" name="verifyCode">
                            <img id="vCode" src="/Image.do" />  
                            <a href="javascript:changeCode();" class="login-forget primary"> 看不清,换一个</a> 
                        </div>

</div>

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int w = 70, h = 40;
        String validateCode=CodeUtil.generateVerifyCode(4);
        request.getSession().setAttribute("validateCode", validateCode);//必须放在方法调用的前面
        CodeUtil.outputImage(w,h,response.getOutputStream(),validateCode);
}


完毕!

你可能感兴趣的:(java,图形验证码生成工具)