package com.zpc.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
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 VertifyImageDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//5、设置浏览器content-type头信息,以何种方式打开
response.setContentType("image/jpeg");
//6、设置缓存信息
response.setHeader("Expires", "-1");
response.setHeader("Cache-COntrol", "no-cache");
response.setHeader("Pragma", "no-cache");
//1、内存你中创建图片
BufferedImage image = new BufferedImage(80, 20,BufferedImage.TYPE_INT_RGB);
//2、得到图片
Graphics graphics = image.getGraphics();
//3、设置图片信息
graphics.setColor(Color.RED);
graphics.setFont(new Font(null,Font.BOLD,20));
graphics.drawString(makeStr(),0, 20);
//4、写给浏览器
ImageIO.write(image, "jpg", response.getOutputStream());
}
private String makeStr() {//产生7位数字
Random random = new Random();
String num = random.nextInt(999999)+"";
StringBuffer sb = new StringBuffer();
for(int i=0;i<7-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);
}
}
输出随机数字的认证图片
最新推荐文章于 2024-09-10 10:21:38 发布