生成验证码图片

来源:互联网 发布:c罗各项数据 编辑:程序博客网 时间:2024/06/05 04:58

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 
//设置内容输出类型为jpeg图片(别的格式也都可以)
response.setContentType("image/jpeg");


//清除缓存(清除原本生成的信息,因为点击验证码图片的时候要产生新的随机验证码)

response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setHeader("expires", "0");
                //Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to                         //test for the presence of a header before setting its value.

//指定验证码内容的数据范围---没有0和O---可以加入中文字符     可根据需要修改
String scope = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz";  


//验证码长度为4个字符    可根据需要修改
int length = 4;


//指定验证码图片的大小    可根据需要修改
int width = 80;
int height = 25;


//产生随机对象----参考Random类
Random rd = new Random();


//生成验证码的字符串(字符串拼接)
String valCode = "";

for(int i=0; i<length; i++){
valCode += scope.charAt(rd.nextInt(scope.length()));
}


//获取session对象
 HttpSession session = request.getSession();


//将验证码存入session
session.setAttribute("valCodeInSession", valCode);


//创建画布
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);


//从画布上获取画笔
Graphics g = img.getGraphics();


//画出底色为浅灰色的矩形   可根据需要修改
g.setColor(Color.lightGray);
g.fillRect(0, 0, width, height);//实心矩形 


//画出10条干扰线,颜色随机,位置随机   可根据需要修改
for(int i=0; i<10; i++){
g.setColor(new Color(rd.nextInt(255), rd.nextInt(255), rd.nextInt(255)));//0-254之间随机取值
g.drawLine(rd.nextInt(width), rd.nextInt(height), rd.nextInt(width), rd.nextInt(height));
}

                         //字体数组
Font[] fonts = {new Font("宋体", Font.BOLD, 20), new Font("隶书", Font.BOLD, 18), new Font("黑体", Font.BOLD, 22)};

//画出验证码的内容
for(int i=0; i<length; i++){


//随机设置颜色   可根据需要修改
g.setColor(new Color(rd.nextInt(100), rd.nextInt(100), rd.nextInt(100)));


//随机设置字体   可根据需要修改
g.setFont(fonts[rd.nextInt(fonts.length)]);

//旋转文字    可根据需要修改
Graphics2D g2d = (Graphics2D)g;
AffineTransform trans = new AffineTransform();
trans.rotate(rd.nextInt(45)*3.14/180, 15*i+10, 7);
g2d.setTransform(trans);

//画出单个字符    随机设置字符高度  可根据需要修改
g.drawString(valCode.charAt(i) + "", width * i / length + 5, rd.nextInt(5) + 15);
}


//释放画笔
g.dispose();


//生成图片
ImageIO.write(img, "JPEG", response.getOutputStream());

}


action验证码示例

package com.uan.action;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.util.Random;import javax.imageio.ImageIO;import javax.imageio.stream.ImageOutputStream;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.interceptor.ServletResponseAware;import com.opensymphony.xwork2.Action;//Struts 2方式---type=streampublic class ValCodeAction extends BaseAction implements ServletResponseAware {private HttpServletResponse response;private InputStream inputStream;   //类型为stream的返回结果需要一个字节数组输入流public InputStream getInputStream() {return inputStream;}@Overridepublic String execute() throws Exception {//设置内容输出类型为jpeg图片response.setContentType("image/jpeg");//清除缓存response.setHeader("pragma", "no-cache");response.setHeader("cache-control", "no-cache");response.setHeader("expires", "0");//指定验证码内容的数据范围---没有0和O---可以加入中文字符     可根据需要修改//String scope = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz";  String scope = "123456789";  //验证码长度为4个字符    可根据需要修改int length = 4;//指定验证码图片的大小    可根据需要修改int width = 80;int height = 25;//产生随机对象----参考Random类Random rd = new Random();//生成验证码的字符串String valCode = "";for(int i=0; i<length; i++){valCode += scope.charAt(rd.nextInt(scope.length()));}//将验证码存入sessionsession.put("valCodeInSession", valCode);//创建画布BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//从画布上获取画笔Graphics g = img.getGraphics();//画出底色为浅灰色的矩形   可根据需要修改g.setColor(Color.lightGray);g.fillRect(0, 0, width, height);//画出10条干扰线,颜色随机,位置随机   可根据需要修改for(int i=0; i<10; i++){g.setColor(new Color(rd.nextInt(255), rd.nextInt(255), rd.nextInt(255)));g.drawLine(rd.nextInt(width), rd.nextInt(height), rd.nextInt(width), rd.nextInt(height));}Font[] fonts = {new Font("宋体", Font.BOLD, 20), new Font("隶书", Font.BOLD, 18), new Font("黑体", Font.BOLD, 22)};//画出验证码的内容for(int i=0; i<length; i++){//随机设置颜色   可根据需要修改g.setColor(new Color(rd.nextInt(100), rd.nextInt(100), rd.nextInt(100)));//随机设置字体   可根据需要修改g.setFont(fonts[rd.nextInt(fonts.length)]);//旋转文字    可根据需要修改Graphics2D g2d = (Graphics2D)g;AffineTransform trans = new AffineTransform();trans.rotate(rd.nextInt(45)*3.14/180, 15*i+10, 7);g2d.setTransform(trans);//画出单个字符    随机设置字符高度  可根据需要修改g.drawString(valCode.charAt(i) + "", width * i / length + 5, rd.nextInt(5) + 15);}//释放画笔g.dispose();//生成图片//ImageIO.write(img, "JPEG", response.getOutputStream());//将图片数据转换为字节数组输出流ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageOutputStream ios = ImageIO.createImageOutputStream(baos);ImageIO.write(img, "jpeg", ios);ios.close();//字节数组输出流中的数据传送到Action的输入流中this.inputStream = new ByteArrayInputStream(baos.toByteArray());return Action.SUCCESS;}@Overridepublic void setServletResponse(HttpServletResponse response) {this.response = response;}}