很久沒寫部落格了,都快忘記這裡有帳號了。好了,不羅嗦,跟大家分享下產生驗證碼圖片代碼
import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;import javax.imageio.stream.FileImageOutputStream;public class ValidateCode {/** * 驗證碼屬性名稱 */public static final String VALIDATE_CODE_NAME = "validate_code";char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };/** * 驗證碼圖片的寬度。 */private int width = 75;/** * 驗證碼圖片的高度。 */private int height = 20;/** * 驗證碼字元個數 */private int codeCount = 4;/** * xx */private int xx = 0;/** * 字型高度 */private int fontHeight;/** * codeY */private int codeY;public ValidateCode() {xx = width / (codeCount + 1);fontHeight = height - 2;codeY = height - 4;}public void getValidateImage() {// 定義映像bufferBufferedImage buffImg = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics2D gd = buffImg.createGraphics();// 建立一個隨機數產生器類Random random = new Random();// 將映像填充為白色gd.setColor(Color.WHITE);gd.fillRect(0, 0, width, height);// 建立字型,字型的大小應該根據圖片的高度來定。Font font = new Font("Fixedsys", Font.BOLD, fontHeight);// 設定字型。gd.setFont(font);// 畫邊框。gd.setColor(Color.BLACK);gd.drawRect(0, 0, width - 1, height - 1);// 隨機產生160條幹擾線,使圖象中的認證碼不易被其它程式探測到。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用於儲存隨機產生的驗證碼,以便使用者登入後進行驗證。StringBuffer randomCode = new StringBuffer();int red = 0, green = 0, blue = 0;// 隨機產生codeCount數位驗證碼。for (int i = 0; i < 4; i++) {// 得到隨機產生的驗證碼數字。String strRand = String.valueOf(codeSequence[random.nextInt(10)]);// 產生隨機的顏色分量來構造顏色值,這樣輸出的每位元字的顏色值都將不同。red = random.nextInt(255);green = random.nextInt(255);blue = random.nextInt(255);// 用隨機產生的顏色將驗證碼繪製到映像中。gd.setColor(new Color(red, green, blue));gd.drawString(strRand, (i + 1) * xx, codeY);// 將產生的四個隨機數組合在一起。randomCode.append(strRand);}try {FileImageOutputStream writeImage = new FileImageOutputStream(new File("c:\\pic.jpg"));ImageIO.write(buffImg, "jpeg", writeImage);writeImage.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void main(String[] args) {ValidateCode vc = new ValidateCode();vc.getValidateImage();}}