package com.it.test;
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 Test05 extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
private static final int width=120;//长
private static final int longth=24;//宽
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image=new BufferedImage(width, longth, BufferedImage.TYPE_INT_RGB);//创建 一个 验证码的框
Graphics g=image.getGraphics();//实例化对象g为绘画类
setBackground(g);//设置背景颜色
setBorder(g);//设置框内颜色和大小
setNumber(g);//设置随机数,不能与setBorder调换,会被覆盖的
setLine(g);//设置干扰线
//response.setHeader("refresh", "10");
response.setContentType("image/jpeg");//设置图片类型
ImageIO.write(image, "jpg", response .getOutputStream());//输出图片
}
private void setBorder(Graphics g) {
// TODO Auto-generated method stub
//g.setColor(Color.blue);//框内 颜色为蓝色,蓝色 上档次,
g.setColor(Color.GRAY);//尽管蓝色 上档次,但是会覆盖红色,这里选灰色
g.fillRect(1, 1, width-2, longth-2);
}
private void setNumber(Graphics g) {
// TODO Auto-generated method stub
g.setColor(Color.RED);
g.setFont(new Font("",Font.BOLD,18));
String numRand="";
for(int i=0;i<4;i++)//4个随机数字
{
String rand=String.valueOf(new Random().nextInt(10));
numRand+=rand;
g.drawString(rand, 24*i+new Random().nextInt(3)*i+8, 20);
}
}
private void setLine(Graphics g) {
// TODO Auto-generated method stub
//g.setColor(Color.RED);//定义线的颜色为红色,红色大气
g.setColor(Color.BLUE);//红色固然大气,会影响验证,选用蓝色
for(int i=0;i<5;i++)//画五条线
{
int x1= new Random().nextInt(width);
int y1= new Random().nextInt(longth);
int x2= new Random().nextInt(width);
int y2= new Random().nextInt(longth);
g.drawLine(x1, y1, x2, y2);
}
}
private void setBackground(Graphics g) {
// TODO Auto-generated method stub
g.setColor(Color.WHITE);//大写 显示逼格
g.fillRect(0, 0, width, longth);
}
}
web开发 写一个数字验证码
最新推荐文章于 2021-05-22 16:04:35 发布