首頁 > Java > Java入門 > 主體

java實作動態圖片驗證碼

王林
發布: 2020-01-09 17:21:48
轉載
2434 人瀏覽過

java實作動態圖片驗證碼

目的:

防止惡意表單註冊

產生驗證碼圖片

##1、定義寬高

int width = 100;
int height = 50;
登入後複製

2、使用BufferedImage在記憶體中產生圖片

r​​rreee

3、繪製背景和邊框

(免費學習影片教學分享:

java影片教學

4、建立隨機字元集和隨機數物件

Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
登入後複製

5、建立隨機色彩產生方法

//字符集
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgjijklmnopqrstuvwxyz";

//随机数
Random ran = new Random();
登入後複製

6、繪製驗證碼字元

private Color getRandomColor(Random random) {
    //获取随机颜色
    int colorIndex = random.nextInt(3);
    switch (colorIndex) {
        case 0:
            return Color.BLUE;
        case 1:
            return Color.GREEN;
        case 2:
            return Color.RED;
        case 3:
            return Color.YELLOW;
        default:
            return Color.MAGENTA;
    }
}
登入後複製

7、繪製幹擾線

//绘制验证码
for (int i = 0; i < 4; i++) {
    //获取随机字符
    int index = ran.nextInt(str.length());
    char ch = str.charAt(index);
    //获取随机色
    Color randomColor = getRandomColor(ran);
    g.setColor(randomColor);
    //设置字体
    Font font = new Font("宋体", Font.BOLD, height / 2);
    g.setFont(font);
    //写入验证码
    g.drawString(ch + "", (i == 0) ? width / 4 * i + 2 : width / 4 * i, height - height / 4);
}
登入後複製

8、使用ImageIO輸出圖片java實作動態圖片驗證碼r​​rreee

實現刷新效果

1、新html頁面

2、使用img標籤實作圖片展示

//干扰线
for (int i = 0; i < 10; i++) {
    int x1 = ran.nextInt(width);
    int x2 = ran.nextInt(width);
    int y1 = ran.nextInt(height);
    int y2 = ran.nextInt(height);
    Color randomColor = getRandomColor(ran);
    g.setColor(randomColor);
    g.drawLine(x1, x2, y1, y2);
}
登入後複製

3、使用js實作刷新效果

ImageIO.write(image, "jpg", resp.getOutputStream());
登入後複製

最終效果圖:java實作動態圖片驗證碼

相關文章教學推薦:

java入門教學######

以上是java實作動態圖片驗證碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:csdn.net
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!