验证码的简单封装

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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值