Java 驗證碼生成代碼,生成樣式
依賴:生成隨機的字符類
生成的圖片:

源代碼:
/**
* 生成驗證碼
*
* @author zgcwkj
* @since 2019-01-11
*/
public class ValidateCode {
private String validateCode = "";
private String validateColor = "FFFFFF";
/**
* 實例驗證碼
*/
public ValidateCode() {
validateCode = new RandomCode(true, true, false).getRandom(4);
}
/**
* 實例驗證碼
*/
public ValidateCode(int length) {
validateCode = new RandomCode(true, true, false).getRandom(length);
}
/**
* 獲取驗證碼
*/
public String GetValidate() {
return validateCode;
}
/**
* 背景顏色 不傳參數時為隨機
*/
public void GetColor() {
validateColor = new RandomCode(true, false, false).getRandom(6);
}
/**
* 背景顏色 不傳參數時為隨機
*/
public void GetColor(String color) {
validateColor = color;
}
/**
* 獲取生成的圖片
*
* @param RandomText 隨機碼
* @return
*/
public BufferedImage getImage() {
// 創建緩存
BufferedImage bi = new BufferedImage(validateCode.length() * 20, 35, BufferedImage.TYPE_INT_RGB);
// 獲得畫布
Graphics g = bi.getGraphics();
// 設置顏色
g.setColor(new Color(Integer.parseInt(validateColor, 16)));
// 填充區域
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
// 設置顏色
g.setColor(Color.lightGray);
// 畫圖片的背景噪音線
for (int i = 0; i < 12; i++) {
int x1 = new Random().nextInt(bi.getWidth());
int y1 = new Random().nextInt(bi.getHeight());
int x2 = new Random().nextInt(bi.getWidth());
int y2 = new Random().nextInt(bi.getHeight());
g.drawLine(x1, y1, x2, y2);
}
Graphics2D g2d = (Graphics2D) g;// 轉換為Graphics2D類型
Font font = new Font("Georgia", Font.BOLD, 25); // 創建字體對象
g2d.setFont(font); // 設置字體
// 創建循環漸變的GraphientPaint對象
GradientPaint paint = new GradientPaint(0, 0, Color.BLUE, bi.getWidth(), bi.getHeight(), Color.GRAY, true);
g2d.setPaint(paint);// 設置漸變
g2d.drawString(validateCode, 5, (bi.getHeight() + 10) / 2); // 繪制文本
// 設置顏色
g.setColor(Color.WHITE);
// 畫圖片的前景噪音點
for (int i = 0; i < 10; i++) {
int x1 = new Random().nextInt(bi.getWidth());
int y1 = new Random().nextInt(bi.getHeight());
int x2 = new Random().nextInt(bi.getWidth());
int y2 = new Random().nextInt(bi.getHeight());
g.drawLine(x1, y1, x2, y2);
}
return bi;
}
}
使用:
ValidateCode validateCode = new ValidateCode(6);
String random = validateCode.GetValidate();
BufferedImage image = validateCode.getImage();
源碼下載:ValidateCode.java
版權屬於:zgcwkj
本文鏈接:https://www.zgcwkj.com/archives/78.html
轉載聲明:請注明本文章的標題及內容的出處和聲明,謝謝
評論已關閉