服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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

  本文将教你如何一步一步地使用javabean实现了产生彩色验证码的全过程,并提供源代码。



 


 文件名: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());

%>





扫描关注微信公众号