论坛数据统计           欢迎到【弱电论坛】来学习和讨论问题!

★电工电气产品供求、电气展会、人才、电气技术文章、图库、电气技术论坛等相关内容,请跳转至【电气之家网】--- 可直接使用本站会员名和密码登陆!(首次使用需要激活账户)
标王 热搜: 网络监控  弱电  楼宇对讲  机房及机柜内部的理线方法  CAD  门禁  综合布线  ar800-hn  工资  面板 
 
 
当前位置: 首页 » 技术 » 电脑技术 » 网页网站 » 正文

java生成验证码图片

放大字体  缩小字体 发布日期:2013-01-21  浏览次数:233
 
 
这是jsp页面,起个名字例如叫image.jsp:

<%@ page contentType="image/JPEG"   
    import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"   
    pageEncoding="GBK"%><%!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 < 100; 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("code", sRand);    
    
    g.dispose();    

    ImageIO.write(image, "JPEG", response.getOutputStream());  

///以下代码保证输出不报错。

    out.clear();

    out=pageContext.pushBody();

 

 

%>


在你需要引入的地方:
<img border=0 src="image.jsp">

就可以了。。。
 
 
 
[ 技术搜索 ]  [ 加入收藏 ]  [ 告诉好友 ]  [ 打印本文 ]  [ 关闭窗口 ]

 
0条 [查看全部]  相关评论

 
点击排行
 
 
 
弱电基础 | 常用软件 | 信息发布规则 | 积分规则 | VIP会员注册 | 广告投放 | 弱电培训 | 联系我们 | 版权声明 | 帮助中心 | 网站地图 | 排名推广 | 京ICP备11008917号-3 | RSS订阅
★本站手机app客户端已上线! 点击下载