日期:2014-05-18 浏览次数:20863 次
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
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);
}
%>
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
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="";
for (int i=0;i<4;i++){
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110 g.drawString(rand,13*i+6,16);
}
session.setAttribute("rand",sRand);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
%>
------解决方案--------------------
楼上的可以,是“我的智囊团”教程里的代码,没问题。
------解决方案--------------------
网上有很多,不过你要做的跟网上差不多的话还得学会自己改
------解决方案--------------------
用之前,最好先了解一下验证码的原理。
验证码的图片是服务器端动态生成的,上面的字母、数字什么的都是服务端随机生成的写到图片流中去的,
同时在 session 中记录下这些字符,待用户提交后首先判断用户输入的值是否与 session 中的值相同,
相同的话,说明是正确的,否则就是不对的。
验证码一般采用 Servlet 来实现,也就是说前台页面 img 里的 src 是一个 Servlet 地址。