JAVA-簡單實現驗證碼產生

來源:互聯網
上載者:User

標籤:rac   public   img   awt   填充   value   矩形   微軟   demo   

package demo;import java.awt.BasicStroke;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;/** * 驗證碼 *  * @author Weirdo-world * */public class Demo1 {    public static void main(String[] args) {        for (int i = 0; i < 10; i++) {            verificationCode(6);        }    }    // 驗證碼產生    public static void verificationCode(int n) {        String str = "abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";        char[] ch = new char[n];        int w = n * 20 + 10;        int h = 40;        Random r = new Random();        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);// 建立映像寬高        Graphics2D g = (Graphics2D) img.getGraphics();        g.setColor(Color.WHITE);// 顏色設定        g.fillRect(0, 0, w, h); // 填充指定矩形        int x = 10;        g.setFont(new Font("微軟雅黑", Font.BOLD, 15));// 字型設定        for (int i = 0; i < n; i++) {            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));// 隨機顏色            ch[i] = str.charAt(r.nextInt(str.length()));            int y = r.nextInt(20) + 15;            g.drawString(String.valueOf(ch[i]), x, y);            x += 20;        }        // 字母數字幹擾        int nn = r.nextInt(n * 4) + 10;        char[] chs = new char[nn];        int xx = 10;        for (int i = 0; i < nn; i++) {            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(100) + 10));            chs[i] = str.charAt(r.nextInt(str.length()));            int y = r.nextInt(20) + 10;            g.drawString(String.valueOf(chs[i]), xx, y);            xx += 8;        }        // 線條幹擾        for (int i = 0; i < nn; i++) {            g.setStroke(new BasicStroke(r.nextInt(3)));            g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(100) + 10));            int x1 = r.nextInt(w);            int y1 = r.nextInt(h);            int x2 = r.nextInt(w);            int y2 = r.nextInt(h);            g.drawLine(x1, y1, x2, y2);//        }        try {            ImageIO.write(img, "jpg", new File("g:/image/tmp/" + new String(ch) + ".jpg"));        } catch (IOException e) {            e.printStackTrace();        }    }}

 

JAVA-簡單實現驗證碼產生

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.