• 验证码 Demo


     1         //设置响应头
     2         response.setCharacterEncoding("image/jpeg");
     3         int width=160;
     4         int height=40;
     5         BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     6         Graphics g=image.getGraphics();
     7         Graphics2D g2d = (Graphics2D) g;
     8         g2d.setColor(Color.WHITE);
     9         g2d.fillRect(0, 0, width, height);
    10         g2d.setFont(new Font("宋体", Font.BOLD, 18));
    11          Random random=new Random();
    12         for(int i=0;i<4;i++)//获取随机四个汉字
    13         {
    14             Color c=new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    15             String s=GetStr();
    16             
    17             AffineTransform aff = new AffineTransform();
    18             aff.rotate(Math.random(),i*10,height-20);//旋转
    19             aff.scale(0.2+Math.random(), 0.2+Math.random());//缩放
    20             g2d.setTransform(aff);
    21             System.err.println(">:"+s);        
    22             
    23             g2d.setColor(c);
    24             g2d.drawString(s, i*10, height- 5);
    25         }
    26         
    27         for(int i=0;i<3;i++)    //干扰线
    28         {
    29             Color c=new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    30             g2d.setColor(c);
    31             g2d.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
    32             
    33         }
    34         g2d.dispose();//图片生效
    35         ImageIO.write(image, "jpeg", response.getOutputStream());//输出    
    36         System.out.println("输出");
    37     }
    38     
    39     //获取汉字
    40     private static String GetStr()
    41     {
    42         String str = null;
    43         try {
    44             
    45             int hightPos, lowPos; // 定义高低位
    46             Random random = new Random();
    47             hightPos = (176 + Math.abs(random.nextInt(39)));//获取高位值
    48             lowPos = (161 + Math.abs(random.nextInt(93)));//获取低位值
    49             byte[] b = new byte[2];
    50             b[0] = (new Integer(hightPos).byteValue());
    51             b[1] = (new Integer(lowPos).byteValue());
    52             str = new String(b, "GBK");//转成中文
    53             
    54         } catch (Exception e) {
    55             e.printStackTrace();
    56         }
    57         return str;
    58         
    59     }

     PS:写验证码不能把所有的都用上,这样就无法识别了,可以选择其中的几种进行,如写汉字只加干扰线,写字母加旋转等。

  • 相关阅读:
    c# 文件上传
    iOSswift基础篇1
    copyWithZone 的使用方法
    客户端登陆接收大量数据导致数据丢失问题解决方法
    设计模式观察者模式(KVO)
    SQLite 之 C#版 System.Data.SQLite 使用
    设计模式MVC(C++版)
    JS 创建自定义对象的方法
    手机号、邮箱、身份证号 格式 验证
    在.cs文件中添加客户端方法
  • 原文地址:https://www.cnblogs.com/liuwt365/p/4122977.html
Copyright © 2020-2023  润新知