如何用自定义标签实现图片验证码?

vipwalkingdog 2012-01-16 04:08:16
如题。

public class RandomPic extends TagSupport
{
@Override
public int doEndTag() throws JspException
{

int width=100, height=18, r1, g1, b1;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
r1=200+random.nextInt(50);
g1=200+random.nextInt(50);
b1=200+random.nextInt(50);
g.setColor(new Color(r1, g1, b1));
g.fillRect(1, 1, width-1, height-1);
g.setColor(new Color(102,102,102));
g.drawRect(0, 0, width-1, height-1);
r1=160+random.nextInt(40);
g1=160+random.nextInt(40);
b1=160+random.nextInt(40);
g.setColor(new Color(r1, g1, b1));
for (int i=0;i<155;i++)
{
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g.drawLine(x,y,x + xl,y + yl);
}
for (int i = 0;i < 70;i++)
{
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int xl = random.nextInt(12) + 1;
int yl = random.nextInt(6) + 1;
g.drawLine(x,y,x - xl,y - yl);
}
String sRand="";
for (int i=0;i<6;i++)
{
String tmp="";
long itmp = 0;
char ctmp = '\u0000';
switch ((int)Math.round(Math.random() * 2))
{
case 1:
itmp = Math.round(Math.random() * 25 + 65);
ctmp = (char)itmp;
tmp = String.valueOf(ctmp);
break;
case 2:
itmp = Math.round(Math.random() * 25 + 97);
ctmp = (char)itmp;
tmp = String.valueOf(ctmp);
break;
default :
itmp = Math.round(Math.random() * 9);
tmp = String.valueOf(itmp);
}
sRand += tmp;
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
g.drawString(tmp,15*i+10,15);
}

g.dispose();

//已经配置好tld了。应该这样直接输出图片?前提是图片不用保存在服务器上。
/**
* <Random:RandomPic/>
* 上面一句会输出一张图片,
*
*
*/
//ImageIO.write(image, "jpeg", pageContext.getOut());
return EVAL_PAGE;
}
...全文
207 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jiabaafaf 2014-05-23
  • 打赏
  • 举报
回复
解决的代码共享下~
vipwalkingdog 2012-02-20
  • 打赏
  • 举报
回复
已自行解决。
vipwalkingdog 2012-01-16
  • 打赏
  • 举报
回复
不好意思,补充下。
代码中注销的部分就是问题。

67,538

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧