java仿Servlet生成驗證碼實例詳解
更新時間:2017年04月27日 10:11:46 投稿:lqh
這篇文章主要介紹了java仿Servlet生成驗證碼實例詳解的相關(guān)資料,需要的朋友可以參考下
java仿Servlet生成驗證碼實例詳解
實現(xiàn)原理:使用BufferedImage對象的Graphics來進行繪制,然后輸出成一張圖片進行保存
實現(xiàn)代碼及詳解:
public class validateCode{
private static Random rand = new Random();
public static void main(String[] args){
int val1 = rand.nextInt(9);
int val2 = rand.nextInt(9);
int val3 = rand.nextInt(9);
int val4 = rand.nextInt(9);
String val = val1 + " " + val2 + " " + val3 + " " + val4'
BufferedImage buf = drawImage(val);
//將最終的圖片保存到D://cheng.png下
ImageIO.write(buf,"png",new File("D://cheng.png");
}
public static BufferedImage drawImage(String code){
int height = 30;
int width = 60;
BufferedImage buf = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D gs = buf.createGraphics();
gs.setBackground(Color.black);
gs.drawRect(0,0,width,height);
//繪制隨機干擾線
int total = 100;
drawRandLine(gs,total);
//繪制驗證碼
Font font = new Font("行楷",Font.BOLD,20);
gs.setFont(font);
gs.setColor(getRandColor(155,255));
gs.drawString(code,5,20);
return buf;
}
public static void drawRandLine(Graphics2D gs,int total){
for(int i=0; i<total; i++){
int x1 = rand.nextInt(width);
int x2 = rand.nextInt(width);
int y1 = rand.nextInt(height);
int y2 = rand.nextInt(height);
//設(shè)置隨機顏色
gs.setColor(getRandColor(0,155));
gs.drawLine(x1,y1,x2,y2);
}
}
public static Color getRandColor(int from,int to){
int r = from + rand.nextInt(to-from);
int g = from + rand.nextInt(to-from);
int b = from + rand.nextInt(to-from);
return new Color(r,g,b);
}
最終實現(xiàn)效果圖

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Spring Cloud Zuul路由規(guī)則動態(tài)更新解析
這篇文章主要介紹了Spring Cloud Zuul路由規(guī)則動態(tài)更新解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11
使用java生成json時產(chǎn)生棧溢出錯誤問題及解決方案
這篇文章主要介紹了使用java生成json時產(chǎn)生棧溢出錯誤問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringBoot集成Lettuce客戶端操作Redis的實現(xiàn)
本文主要介紹了SpringBoot集成Lettuce客戶端操作Redis的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11
Mybatis執(zhí)行SQL時多了一個limit的問題及解決方法
這篇文章主要介紹了Mybatis執(zhí)行SQL時多了一個limit的問題及解決方法,Mybatis攔截器方法識別到配置中參數(shù)supportMethodsArguments 為ture時會分頁處理,本文結(jié)合示例代碼給大家講解的非常詳細,需要的朋友可以參考下2022-10-10
Spring中@Async注解執(zhí)行異步任務(wù)的方法
在業(yè)務(wù)處理中,有些業(yè)務(wù)使用異步的方式更為合理,這篇文章主要介紹了Spring中@Async注解執(zhí)行異步任務(wù)的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06

