自我補充篇之java隨機驗證碼的生成(字母不同色,干擾線無規律顏色也不同)

圖片效果:

                         

<!--
	自我補充篇之java隨機驗證碼的生成
	Goal:利用java代碼生成隨機驗證碼的圖片(今天終於想起寫這個了)!
-->

我的驗證碼的優勢:每個字母的顏色不同~,大小寫字母數字混合,干擾線無規律,顏色也不同!
缺點:有點傳統
代碼:
public static void main(String[] lovingshu){
	//Create a image in RAM
	BufferedImage bufImage=new BufferedImage(100,30,BufferedImage.TYPE_3BYTE_BGR);
	//get the paint of the image in RAM
	Graphics gra=bufImage.getGraphics();
	//seed of random
	Random ran=new Random();
	//fill the background
	gra.setColor(Color.WHITE);
	gra.fillRect(0, 0, 100, 30);
	//the String of code
	String vliCode="";
	//set font
	gra.setFont(new Font("微軟雅黑",Font.ITALIC,20));
	//start to draw the letter
	while(vliCode.length()<4){
		gra.setColor(new Color(ran.nextInt(255)+1,ran.nextInt(255)+1,ran.nextInt(255)+1));
		String tmp="";
		//the style of the code
		switch(ran.nextInt(3)){
		case 0:
			tmp=(char)(ran.nextInt(26)+65)+"";
			break;
		case 1:
			tmp=(char)(ran.nextInt(26)+97)+"";
			break;
		default:
			tmp=ran.nextInt(10)+"";
			break;
		}
		//start to draw
		gra.drawString(tmp,10+vliCode.length()*20,20);f
		//remeber to add the chapter
		vliCode+=tmp;
	}
	//draw the interference line
	for(int i=0;i<(ran.nextInt(5)+5);i++){
		gra.setColor(new Color(ran.nextInt(255)+1,ran.nextInt(255)+1,ran.nextInt(255)+1));
		gra.drawLine(ran.nextInt(100),ran.nextInt(30),ran.nextInt(100),ran.nextInt(30));
	}	
	//out put the image
	try {
		/*
		*if you want it be output at the Client,do as follows:
		*ImageIO.write(bufImage,"JPEG",response.getOutputStream());
		*/
		File fi=new File("E:\\ValidateCode.jpg");//this is the path
		ImageIO.write(bufImage,"jpeg",fi);
		if(fi.exists()){
			System.out.println("Success!");
		}else{
			System.out.println("Failed!");
		}
	} catch (IOException e) {
		e.printStackTrace();
	}finally{
		System.out.println("Lovingshu's Forever");
	}
}
<!--
Author:Lovingshu's Forever
Date:2011-11-08 22:34
Remark:Suddenly,I think up that my hobby is programming~not gaming!
-->
發佈了62 篇原創文章 · 獲贊 5 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章