在Java中,你可以使用以下方法生成隨機驗證碼:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.util.Random;
public static String generateRandomVerificationCode(int codeLength) {
// 定義驗證碼字符集
String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder verificationCode = new StringBuilder();
Random random = new Random();
for (int i = 0; i < codeLength; i++) {
int randomIndex = random.nextInt(charSet.length());
char randomChar = charSet.charAt(randomIndex);
verificationCode.append(randomChar);
}
return verificationCode.toString();
}
public static void drawVerificationCode(String verificationCode, int width, int height, File outputFile) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.BLACK);
int fontSize = height / verificationCode.length();
graphics.setFont(new Font("Arial", Font.PLAIN, fontSize));
for (int i = 0; i < verificationCode.length(); i++) {
String charAtI = String.valueOf(verificationCode.charAt(i));
graphics.drawString(charAtI, i * fontSize, (i + 1) * fontSize);
}
ImageIO.write(image, "png", outputFile);
graphics.dispose();
}
public static void main(String[] args) {
int codeLength = 6; // 驗證碼長度
int width = 200; // 圖像寬度
int height = 80; // 圖像高度
File outputFile = new File("verificationCode.png"); // 輸出文件路徑
try {
String verificationCode = generateRandomVerificationCode(codeLength);
drawVerificationCode(verificationCode, width, height, outputFile);
System.out.println("驗證碼已生成并保存到: " + outputFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
運行這個程序,它將生成一個包含隨機驗證碼的圖像,并將其保存到指定的文件中。你可以根據需要調整驗證碼的長度、圖像尺寸和輸出文件路徑。