欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

生成随机图片作验证码

程序员文章站 2022-07-14 13:18:04
...

生成图片主要用到了一个BufferedImage类,

生成随机图片作验证码

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
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 ResponseDemo2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    	//设置refresh响应头控制浏览器每隔5秒钟刷新一次
    	response.setHeader("refresh", "5");
    	//1.在内存中创建一张图片
    	BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
    	//2.得到图片
    	Graphics2D g = (Graphics2D) image.getGraphics();
    	g.setColor(Color.white);//背景色
    	g.fillRect(0, 0, 80, 20);
    	//3.向图片上写数据
        g.setColor(Color.BLUE);//设置图片上字体的颜色
        g.setFont(new Font(null, Font.BOLD, 20));
        g.drawString(makeNum(), 0, 20);
        //4.设置响应头控制浏览器浏览器以图片的方式打开
        response.setHeader("Content-Type", "image/jpeg");
        //相当于response.setContentType("image/jpeg");
        
      //5.设置响应头控制浏览器不缓存图片数据
        response.setDateHeader("expries", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        //6.将图片写给浏览器
        ImageIO.write(image, "jpg", response.getOutputStream());
    }
    /**
     * 生成随机数字
     * @return
     */
    private String makeNum(){
        Random random = new Random();
        String num = random.nextInt(9999)+"";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4-num.length(); i++) {
            sb.append("0");
        }
        num = sb.toString()+num;
        return num;
    }



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