验证码的简单封装

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34457118/article/details/78022520
package cn.itcast.response;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Chackcode extends HttpServlet {

private static final long serialVersionUID = 1L;

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

//      第一步,在内存中生成图片
//      第二步,获得笔的对象
//      第三步,准备好数据,随机生成4个字符画在纸上
//      第四步,对纸上的字符进行加干扰

            //验证框大小
        int width = 120;
        int height = 30;

        //获得画笔
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
         Graphics2D g = (Graphics2D) image.getGraphics();

//       设置验证图片的背景颜色并填充
         g.setColor(Color.GRAY);
         g.fillRect(0,0,width,height);

//       设置边框颜色并画边框
         g.setColor(Color.BLUE);
         g.drawRect(0, 0, width-1, height-1);

//       准备数据,也可使用文字字符
         String words = "QWERTYUIOPLKJHGFDASZXCVBBMNMqwertyuioplkjhgfdsazxcvbnm123456789";

        //设置随机字符
         Random random = new Random();

        //设置干扰线的参数
         g.setColor(Color.BLACK);
         int x = 20;
         int y = 20;
         int x1, x2, y1, y2;

        //设置显示的字体
         g.setFont(new Font("隶书",Font.BOLD,20));

         for(int i=0;i<4;i++)
         {
             //字符的旋转
             int jiaodu = random.nextInt(90)-45;
             double hudu = jiaodu*Math.PI/180;
             g.rotate(hudu, x, y);

             int index = random.nextInt(words.length());
             char ch = words.charAt(index);
             //打印字符
             g.drawString(""+ch, x, y);
             //对字符旋转
             g.rotate(-hudu, x, y);
             x+=20;


             x1 = random.nextInt(width);
             y1 = random.nextInt(height);
             x2 = random.nextInt(width);
             y2 = random.nextInt(height);

             //      画干扰线
             g.drawLine( x1, y1, x2, y2);

         }


//      输出到客户端
        ImageIO.write(image, "jpg",response.getOutputStream());
    }

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

}

猜你喜欢

转载自blog.csdn.net/qq_34457118/article/details/78022520
今日推荐