Java 產生隨機驗證碼

來源:互聯網
上載者:User
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * CodeImageGenerator.java
 *
 * @author        <a href="mailto:eroclu@gmail.com">Andy Lu</a>
 * @version       1.0
 */
public final class CodeImageGenerator {
    private final static int DEF_WIDTH = 60;
    private final static int DEF_HEIGHT = 20;
   
    private String code;
    private int width;
    private int height;   
    private BufferedImage image;
   
    public CodeImageGenerator() {
        this(DEF_WIDTH, DEF_HEIGHT);
    }
   
    public CodeImageGenerator(int width, int height) {
        this.width = width;
        this.height = height;
        generateCodeImage();
    }
   
    private void generateCodeImage() {       
        // create the image
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);       
        Graphics g = image.getGraphics();
       
        // set the background color       
        g.setColor(new Color(0xDCDCDC));   
        g.fillRect(0, 0, width, height);
       
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
       
        // set the font
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

        // create a random instance to generate the codes
        Random random = new Random();
       
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
       
        // generate a random code
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            code += rand;
            g.drawString(rand, 13*i+6, 16);
        }
       
        g.dispose();
    }
   
    public BufferedImage getImage() {
        return image;
    }
   
    public String getCode() {
        return code;
    }
   
    public static void main(String[] args) throws Exception {
        File imgFile = new File("codeImage.jpeg");
        CodeImageGenerator cig = new CodeImageGenerator();
        ImageIO.write(cig.getImage(), "JPEG", imgFile);
    }
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.