M - LOG 인증 코드 생 성 방법

3336 단어
[  ] [Java]   /**
 * 
 */
package org.mspring.platform.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOE http://www.szhaoexport.com/linked/20130311.do xception;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * @author Gao Youbo
 * @since Feb 20, 2012
 */
public class ImageUtils {
    /**
     *        
     * 
     * @param outputStream
     *               
     * @param allowValidateString
     *                        
     * @return
     */
    public static String validateCode(OutputStream outputStream, String allowValidateString) {
        int width = 60;
        int height = 20;

        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //    Image
        Graphics2D g = buffImg.createGraphics(); //       Image        (  )  Graphics    

        //            。
        Random random = new Random();

        g.setColor(Color.decode("#ffffff"));
        g.fillRect(0, 0, width, height); //                

        //     ,                。
        Font font = new Font("Times New Roman", Font.PLAIN, 18);
        //     。
        g.setFont(font);

        //    。
        // g.setColor(Color.blue);
        // g.drawRect(0, 0, width - 1, height - 1);

        //     160    ,                  。
        g.setColor(Color.GRAY);
        for (int i = 0; i < 80; i  ) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x   xl, y   yl);
        }

        // randomCode            ,           。
        StringBuffer randomCode = new StringBuffer();
        int red = 0, green = 0, blue = 0;

        //        。
        for (int i = 0; i < 4; i  ) {
            //             。
            int randomIndex = random.nextInt(allowValidateString.length());
            if (randomIndex == 0)
                randomIndex = 1;
            String strRand = allowValidateString.substring(randomIndex - 1, randomIndex);

            //                ,                  。
            red = random.nextInt(110);
            green = random.nextInt(50);
            blue = random.nextInt(50);

            //                   。
            g.setColor(new Color(red, green, blue));
            g.drawString(strRand, 13 * i   6, 16);

            //               。
            randomCode.append(strRand);
        }
        try {
            ImageIO.write(buffImg, "jpeg", outputStream);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return randomCode.toString();
    }
} http://www.fpfuzhou.com/linked/20130311.do

좋은 웹페이지 즐겨찾기