ImageCode画出随机认证码

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class ImageCode {
 /**
  * 画出随机认证码
  * @param rand 随机数
  * @param out 
  * @return  String 生成的认证码
  */
 public static void WriteImage(String rand,OutputStream out){
   
  int width = 60,height=20;
  //创建一个图形对象,类型为RGB
  BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
  //获取图形上下文对象
  Graphics g = image.getGraphics();
  
  //设置背景色
  g.setColor(Color.GREEN);      //设置颜色 白色
  g.fillRect(0,0,width,height); //填充坐标范围内颜色
  
  //画边框
  g.setColor(Color.black);
  g.drawRect(0,0,width-1,height-1);
  
  //将认证码画入刚画的图象中
  g.setColor(Color.black);
  g.setFont(new Font("Times New Romm",Font.PLAIN,18));
  g.drawString(rand,10,15);
  //随机画88个随机干扰点,使认证码不易被其它程序探测到
  Random random = new Random();
  for(int i=0;i<88;i++){
   int x = random.nextInt(width);
   int y = random.nextInt(height);
   g.drawLine(x,y,x,y);
  }
  //释放上下文所有资源
  g.dispose();  
  //输出图象到页面
  try {
   ImageIO.write(image,"JPEG",out);
  } catch (IOException e) {   
   e.printStackTrace();
  }  
  
 }
}

posted on 2007-05-30 11:03 五味子 阅读(180) 评论(0)  编辑  收藏 所属分类: 产生验证码例子

导航

<2025年6月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

统计

留言簿

随笔分类

文章分类

文章档案

搜索

最新评论