在java中生成验证码的问题

来源:互联网 发布:淘宝宝贝介绍模板 编辑:程序博客网 时间:2024/05/18 10:58


@RequestMapping(value = "image", method = RequestMethod.GET)
public void getImage(HttpServletRequest request,
HttpServletResponse response) {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 120, height = 100;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(100, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
g.draw3DRect(0, 0, width - 1, height - 1, true);
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = "";

String  s="012345678901234567890123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789

                             0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

for (int i = 0; i < 4; i++) {
char rand = s.charAt(random.nextInt(s.length()));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(50 + random.nextInt(110), 50 + random
.nextInt(110), 50 + random.nextInt(110)));
// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(String.valueOf(rand), 30 * i + 6, 50);
}
g.drawOval(30, 30, 60, 40);
request.getSession().setAttribute("rand", sRand);
// 图象生效
g.dispose();
ServletOutputStream output = null;
try {
output = response.getOutputStream();
// 输出图象到页面
ImageIO.write(image, "JPEG", output);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}

}

          private 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);
         }


0 0
原创粉丝点击