java生成驗證碼圖片的方法
更新時間:2021年02月25日 10:27:21 作者:相思子~
這篇文章主要為大家詳細介紹了java生成驗證碼圖片的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java生成驗證碼圖片的具體代碼,供大家參考,具體內(nèi)容如下
示例一:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;
public class RandomVerifyCode {
private static final String RANDOM_NUM = "23456789";
private static final String RANDOM_LETTER = "ABCDEFGHJKMNPQRSTUVWXYZ";
private static final String RANDOM_LETTER_SMALL = "abcdefghjkmnpqrstuvwxyz";
private static final String RANDOM_STRING = RANDOM_NUM + RANDOM_LETTER + RANDOM_LETTER_SMALL;
private int width = 95;// 圖片寬
private int height = 25;// 圖片高
private int lineSize = 40;// 干擾線數(shù)量
private int stringNum = 4;// 隨機產(chǎn)生字符數(shù)量
private Random random = new Random();
/**
* 獲得字體
*/
private Font getFont() {
return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
}
/**
* 獲得顏色
*/
private Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc - 16);
int g = fc + random.nextInt(bc - fc - 14);
int b = fc + random.nextInt(bc - fc - 18);
return new Color(r, g, b);
}
/**
* 生成隨機圖片(BASE64格式)
*/
public String getRandcode(HttpServletRequest request, StringBuffer imgBuffer) {
// BufferedImage類是具有緩沖區(qū)的Image類,Image類是用于描述圖像信息的類
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();// 產(chǎn)生Image對象的Graphics對象,改對象可以在圖像上進行各種繪制操作
g.fillRect(0, 0, width, height);//圖片大小
g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字體大小
g.setColor(getRandColor(110, 133));//字體顏色
// 繪制干擾線
for (int i = 0; i <= lineSize; i++) {
drowLine(g);
}
// 繪制隨機字符
String randomString = "";
for (int i = 1; i <= stringNum; i++) {
randomString = drowString(g, randomString, i);
}
g.dispose();
ByteArrayOutputStream out = new ByteArrayOutputStream();
String encode = null;
try {
// 將內(nèi)存中的圖片通過流動形式輸出到客戶端
ImageIO.write(image, "JPEG", out);
encode = "data:image/jpeg;base64,"+Base64.encodeBase64String(out.toByteArray());
out.close();
} catch (Exception e) {
LogHelper.error("登陸控制","驗證碼生成","將內(nèi)存中生成的驗證碼圖片輸出為BASE64格式編碼失敗!");
}
imgBuffer.append(encode);
return randomString;
}
/**
* 繪制字符串
*/
private String drowString(Graphics g, String randomString, int i) {
g.setFont(getFont());
g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
.nextInt(121)));
String rand = String.valueOf(getRandomString(random.nextInt(RANDOM_STRING.length())));
randomString += rand;
g.translate(random.nextInt(3), random.nextInt(3));
g.drawString(rand, 13 * i, 16);
return randomString;
}
/**
* 繪制干擾線
*/
private void drowLine(Graphics g) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.drawLine(x, y, x + xl, y + yl);
}
/**
* 獲取隨機的字符
*/
public String getRandomString(int num) {
return String.valueOf(RANDOM_STRING.charAt(num));
}
public static String randomString(int length){
return RandomStringUtils.random(length, RANDOM_STRING.toCharArray());
}
}
示例二:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class CodeUtil {
private static int width = 90;// 定義圖片的width 90
private static int height = 20;// 定義圖片的height 20
private static int codeCount = 4;// 定義圖片上顯示驗證碼的個數(shù)
private static int xx = 15;
private static int fontHeight = 18;
private static int codeY = 16;
private static char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
public static Map<String,RenderedImage> codePicMap = new HashMap<>();
/**
* 生成一個map集合
* code為生成的驗證碼
* codePic為生成的驗證碼BufferedImage對象
*
* @return
*/
public static Map<String, Object> generateCodeAndPic() {
// 定義圖像buffer
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Graphics2D gd = buffImg.createGraphics();
// Graphics2D gd = (Graphics2D) buffImg.getGraphics();
Graphics gd = buffImg.getGraphics();
// 創(chuàng)建一個隨機數(shù)生成器類
Random random = new Random();
// 將圖像填充為藍色
// gd.setColor(Color.WHITE);
gd.setColor(new Color(232,240,254));
gd.fillRect(0, 0, width, height);
// 創(chuàng)建字體,字體的大小應該根據(jù)圖片的高度來定。
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
// 設置字體。
gd.setFont(font);
// 畫邊框。
gd.setColor(Color.BLACK);
gd.drawRect(0, 0, width - 1, height - 1);
// 隨機產(chǎn)生40條干擾線,使圖象中的認證碼不易被其它程序探測到。
gd.setColor(Color.BLACK);
for (int i = 0; i < 10; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
gd.drawLine(x, y, x + xl, y + yl);
}
// randomCode用于保存隨機產(chǎn)生的驗證碼,以便用戶登錄后進行驗證。
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
// 隨機產(chǎn)生codeCount數(shù)字的驗證碼。
for (int i = 0; i < codeCount; i++) {
// 得到隨機產(chǎn)生的驗證碼數(shù)字。
String code = String.valueOf(codeSequence[random.nextInt(31)]);
// 產(chǎn)生隨機的顏色分量來構造顏色值,這樣輸出的每位數(shù)字的顏色值都將不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// 用隨機產(chǎn)生的顏色將驗證碼繪制到圖像中。
gd.setColor(new Color(red, green, blue));
gd.drawString(code, (i + 1) * xx, codeY);
// 將產(chǎn)生的四個隨機數(shù)組合在一起。
randomCode.append(code);
}
Map<String, Object> map = new HashMap<>();
//存放驗證碼
map.put("code", randomCode);
//存放生成的驗證碼BufferedImage對象
map.put("codePic", buffImg);
return map;
}
public static void main(String[] args) throws Exception {
//創(chuàng)建文件輸出流對象
OutputStream out = new FileOutputStream("D://img/" + System.currentTimeMillis() + ".jpg");
Map<String, Object> map = CodeUtil.generateCodeAndPic();
ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", out);
System.out.println("驗證碼的值為:" + map.get("code"));
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
ZooKeeper官方文檔之Java客戶端開發(fā)案例翻譯
網(wǎng)上有很多ZooKeeper的java客戶端例子,我也看過很多,不過大部分寫的都不好,有各種問題。兜兜轉(zhuǎn)轉(zhuǎn)還是覺得官方給的例子最為經(jīng)典,在學習之余翻譯下來,供朋友們參考2022-01-01
Mybatis批量插入index out of range錯誤的解決(較偏的錯誤)
這篇文章主要介紹了Mybatis批量插入index out of range錯誤的解決(較偏的錯誤),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
如何在Spring?Boot中使用MyBatis訪問數(shù)據(jù)庫
MyBatis可以通過簡單的XML或者注解來配置和映射原始類型,接口,和Java POJO為數(shù)據(jù)庫中記錄,使用MyBatis幫助我們解決各種問題,本文介紹如何在Spring?Boot中使用MyBatis訪問數(shù)據(jù)庫,感興趣的朋友一起看看吧2023-11-11
啟動SpringBoot報錯Input length = 1問題及解決
這篇文章主要介紹了啟動SpringBoot報錯Input length = 1問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

