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();
}
}
}