手机站
网通分站
电信主站
密 码:
用户名:
热门关键字:  虚拟主机  cn域名  域名注册  非法  seo
当前位置 : 主页>程序设计>Java技术>列表

产生彩色验证码_(javabean实现)

来源:互联网 作者:west263.com 时间:2008-02-23 点击:
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!
文件名:Image.java
==================================================================
/*
* Created on 2004-8-4
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package myclass.test;

import java.awt.*;
import java.awt.image.*;
import java.util.*;

/**
* @author
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class Image {

public String sRand="";

public 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);
}
public BufferedImage creatImage(){

// 在内存中创建图象
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(new Color());
//g.drawRect(0,0,width-1,height-1);


// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
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);
}

// 取随机产生的认证码(4位数字)
//String rand = request.getParameter("rand");
//rand = rand.substring(0,rand.indexOf("."));

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);
}
// 图象生效
g.dispose();
return image;
}
}
======================================================================
image.jsp(对bean的引用)

<%@ page contentType="image/jpeg" import="javax.imageio.*" %>
<jsp:useBean id="image" scope="session" class="myclass.test.Image"/>

<%
//设置页面不缓存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);

// 将认证码存入SESSION
session.setAttribute("rand",image.sRand);

// 输出图象到页面
ImageIO.write(image.creatImage(), "JPEG", response.getOutputStream());


%>

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名
注册