代码————刷新验证码

package cn.itcast.response;              

import java.awt.Color;
import java.awt.Font;
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CodeServlet extends HttpServlet {

    /**
     * 实现验证码的操作
    第一步:生成图片
    第二步:生成随机的数字和字母
    第三步:把数字和字母画到图片上
    第四步:把图片显示到页面上
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //生成图片
        int width = 150;
        int height = 50;
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        //得到画笔
        Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
        //生成四个随机的数字和字母
        String words = "asdfghjklqwertyuiopzxcvbASDFGHJKLQWERTYUIOPZXCVB1234567890";
        //创建Random对象
        Random r = new Random();
        int x = 25;
        int y = 30;
        //设置颜色
        g2d.setColor(Color.YELLOW);
        //设置字体的样式
        g2d.setFont(new Font("宋体",Font.BOLD,25));
        //rotate(double theta, double x, double y)
        //弧度=角度*3.14/180
        for(int i=1;i<=4;i++) {
            int idx = r.nextInt(words.length());            
            //根据位置得到具体的字符
            char ch = words.charAt(idx);
            
            //旋转+- 30度
            int jiaodu = r.nextInt(60)-30;
            double hudu = jiaodu*Math.PI/180;
            //旋转的效果
            //g2d.rotate(hudu, x, y);
            //把字符画到图片上
            g2d.drawString(ch+"", x, y);
            
            x += 25;
            
            //转回去
            //g2d.rotate(-hudu, x, y);
        }
        
        //生成三条干扰线
        g2d.setColor(Color.green);
        int x1,y1,x2,y2;
        for(int m=1;m<=3;m++) {
            x1 = r.nextInt(width);
            y1 = r.nextInt(height);
            
            x2 = r.nextInt(width);
            y2 = r.nextInt(height);
            g2d.drawLine(x1, y1, x2, y2);
        }
        //把图片显示到页面上
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
    }

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

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值