验证码----(BufferedImage)

来源:互联网 发布:js 调用支付宝接口 编辑:程序博客网 时间:2024/06/06 05:58

验证码----(BufferedImage)
public class CodeServlet extends HttpServlet {
//写这样一个Servlet让前端获取
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//设置响应头;告诉浏览器我们发的是图片格式的数据
response.setContentType("image/jpeg");
//设置图片的宽高
int width = 70;
int height = 35;
//声明一个RGB格式内存的图片
BufferedImage bImg = new BufferedImage(width,height  ,BufferedImage.TYPE_INT_RGB);
Graphics g = bImg ();
//图片颜色设置为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
//到时我们验证码要放到request中
String code = ""
//设置字体
g.setFont(new Font("宋体",Font.BOLD,16));
//产生并draw4个随机数字,变成一个图片
Random r = new Random();
for(int i=0;i<4;i++){ 
int x = r.nextInt(10);//0-9之间的整数
       int y =10+r.nextInt(20);//让图片中数字位置上下浮动
//设置随机颜色
Color c = new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255));
g.setColor(c);
g.drawString(""+x,i*15,y);
code+=a;
}
request.getSession().setAttribute("sCode", sCode);
for(int i=0;i<4;i++){//画干扰线
Color c = new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255));
g.setColor(c);
g.drawLine(r.nextInt(60), r.nextInt(30), r.nextInt(60), r.nextInt(30));
}
g.dispose();
//发送到前端页面
ImageIO.write(img, "JPEG",response.getOutputStream());
}


}
原创粉丝点击