java仿Servlet生成验证码实例详解
2017-04-27 10:11
686 查看
java仿Servlet生成验证码实例详解
实现原理:使用BufferedImage对象的Graphics来进行绘制,然后输出成一张图片进行保存
实现代码及详解:
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); //设置随机颜色 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); }
最终实现效果图
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
您可能感兴趣的文章:
相关文章推荐
- java生成验证码详解
- Java生成CSV文件实例详解
- Java生成CSV文件实例详解
- Java、Servlet生成验证码由浅到深
- 使用java仿Servlet生成验证码
- [JavaWeb]Servlet验证码实现(实例代码)
- java通过Servlet生成验证码图片
- JSP+Servlet+JavaBean实现登录网页实例详解
- JAVA验证码功能实现(生成验证码的Servlet)
- java随机动态生成汉字验证码图片的实例代码分享
- java生成图片验证码实例代码
- Java 生成随机字符串数组的实例详解
- java通过Servlet生成验证码
- Java 随机生成验证码(支持大小写字母、数字、随机字体)的实例
- Javaweb开发中通过Servlet生成验证码图片
- Javaweb开发中通过Servlet生成验证码图片
- java随机验证码生成实现实例代码
- Java的servlet生成动态验证码
- java生成图片验证码实例代码
- JSP+Servlet+JavaBean实现登录网页实例详解