生成图片验证码

12/12/2015来源:Java教程人气:1779

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

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageServ extends HttpServlet {

/**
*
*/
PRivate static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//阻止页面被缓存,保证每次生成新的验证码
response.setHeader("Pragma", "No-Cache");
response.setHeader("Cache-Control", "no-Cache");
response.setIntHeader("Expires", 0);
//设置响应类型和编码集。
response.setContentType("image/jpeg");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//设置图片大小
int width=100;
int height=20;
//创建图片
BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//绘图
Graphics g=img.getGraphics();
g.setColor(getRandomColor(200, 250));
g.fillRect(1, 1, width-1, height-1);
g.setColor(new Color(100, 100, 100));
g.drawRect(0, 0, width-1, height-1);

Random r=new Random();
//设置验证码
String str=getRadomString(5);
request.getsession().setAttribute("judge", str);
//设置字体
g.setFont(new Font("Arial Black", Font.PLAIN, 16));
for(int i=0;i<str.length();i++){
g.setColor(new Color(100+r.nextInt(110),100+r.nextInt(110),100+r.nextInt(110)));
g.drawString(str.substring(i,i+1), i*15+10, 15);
}
//绘制干扰线
for(int i=0;i<20;i++){
g.setColor(getRandomColor(120,190));
int x0=r.nextInt(width)-1;
int y0=r.nextInt(height)-1;
int x1=r.nextInt(12)+1;
int y1=r.nextInt(6)+1;
g.drawLine(x0, y0, x0+x1,y0+y1);
}
g.dispose();
ImageIO.write(img, "JPEG", response.getOutputStream());
}
/**
*产生随机颜色
* @param fc
* @param bc
* @return
*/
private Color getRandomColor(int fc,int bc){
if(fc>255) fc=255;
if(bc>255) bc=255;
Random r=new Random();
int red=r.nextInt(Math.abs(fc-bc));
int green=r.nextInt(Math.abs(fc-bc));
int blue=r.nextInt(Math.abs(fc-bc));
return new Color(red, green, blue);
}
/**
* 产生随机字符串包含字母数字
* @param size
* @return
*/
private String getRadomString(int size){
StringBuilder sbu=new StringBuilder();
Random r=new Random();
int count=0;
while(count<size){
int index=r.nextInt('z'+1);
char ch=(char)index;
if(Character.isLetterOrDigit(ch)){
sbu.append(ch);
}else{
sbu.append((char)(index%26+(r.nextInt()%2==0?'a':'A')));
}
count++;
}
return sbu.toString();
}
}