页面获得随机码的方法

public static final char[] CHARS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
        'X', 'Y', 'Z', };
public static Random random = new Random();

/**生成一串随即字符
* @return返回字符串String
*/
public static String getRandomString() {
   StringBuffer buffer = new StringBuffer();
   for (int i = 0; i < 4; i++) {
       buffer.append(CHARS[random.nextInt(CHARS.length)]);
   }
   return buffer.toString();
}

/**生成随即颜色
* @return返回颜色对象Color
*/
public static Color getRandomColor() {
//    return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
return new Color(220,220,220);
}

public static Color getReverseColor(Color c) {
   return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c.getBlue());


/**
* 得到随机颜色
* @param fc
* @param bc
* @return
*/
private static Color getRandColor(int fc, int bc) {
       Random random = new Random();
       if (fc > 255)
         fc = 255;
       if (bc > 255)
         bc = 255;
       int r = fc + random.nextInt(bc - fc);
       int g = fc + random.nextInt(bc - fc);
       int b = fc + random.nextInt(bc - fc);
       return new Color(r, g, b);
     }


/**页面获得随机码的方法,生成随机验证码-4位

* @param request
* @param response
* @throws IOException
*/
public void getRandomImg(HttpServletRequest request, HttpServletResponse response) throws IOException{
response.setContentType("image/jpeg");
        String radomString = getRandomString();
        request.removeAttribute("radomString");
        request.getSession(true).setAttribute("radomString", radomString);
        Color color = getRandomColor();
        Color reverse = getReverseColor(color);
        BufferedImage bi = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,18));
        //g.setColor(color);
        g.fillRect(0,0,100,30);
        g.setColor(reverse);
        g.drawString(radomString,14,18);
//        for (int i = 0,n = random.nextInt(100); i<n; i++) {
//            g.drawRect(random.nextInt(100), random.nextInt(30), 1, 1);
//        }
        //背景干扰线
        for (int i = 0; i < 3; i++) {
int x = random.nextInt(100);
int y = random.nextInt(30);
int xl = random.nextInt(100);
int yl = random.nextInt(100);
g.setColor(reverse);
g.drawLine(x, y, x + xl, y + yl);
}
        ServletOutputStream out = response.getOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(bi);
        out.flush();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值