Java驗證碼圖檔生成源代碼
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;
public class Captchautil {
public static String random() {
// 使用字元串來接收随機字元
StringBuffer stringBuffer = new StringBuffer ();
// 所有的小寫字元
String arrWord = "abcdefghigklmnopqrstuvwxyz";
// 使用String.toUpperCase 轉換成大寫字元
String allCase = arrWord.toUpperCase () + arrWord + "1234567890";
// 挑選所有的随機字元串轉化為字元數組
byte[] bytes = allCase.getBytes ();
// 建立随機抽取
Random random = new Random ();
// 擷取4個随機字元并存方法到list集合中
for (int i = 0; i < 4; i++) {
int index = random.nextInt (bytes.length + 1);
// 将對應的ASCII碼值轉換字元存儲
stringBuffer.append ((char)bytes[index]);
}
return stringBuffer.toString ();
}
public static void outputImage(String code, OutputStream ops) {
// 建立Random用來畫幹擾線
Random random = new Random ();
// 建立圖檔對象
BufferedImage image = new BufferedImage (100, 40, BufferedImage.TYPE_3BYTE_BGR);
// 設定畫布
Graphics graphics = image.getGraphics ();
// 設定白色背景
graphics.setColor (Color.white);
graphics.fillRect (0, 0, 100, 40);
byte[] bytes = code.getBytes ();
// 寫字擷取随機顔色
graphics.setColor (new Color (random.nextInt (255) + 1,
random.nextInt (255) + 1,
random.nextInt (255) + 1));
graphics.setFont (new Font ("微軟雅黑", Font.PLAIN, 20));
// 設定驗證碼位置
graphics.drawBytes (bytes, 0, 4, 20, 20);
// 随機線條
for (int i = 0; i < 10; i++) {
graphics.setColor (new Color (random.nextInt (255) + 1,
random.nextInt (255) + 1,
random.nextInt (255) + 1));
graphics.drawLine (random.nextInt (100),
random.nextInt (40),
random.nextInt (100),
random.nextInt (40));
}
try {
boolean write = ImageIO.write (image, "png", ops);
System.out.println (write);
} catch (IOException e) {
e.printStackTrace ();
}
}
public static void main(String[] args){
String code = random ();
System.out.println (code);
try {
// 填寫圖檔的餓導出位置
OutputStream sot = new FileOutputStream ("I:\\file\\a.png", false);
outputImage (code, sot);
} catch (FileNotFoundException e) {
e.printStackTrace ();
}
}
}