JAVA实现验证码主要的代码部分,生成图片以及代码

JAVA实现验证码主要的代码部分,生成图片以及代码

图片示例:

JAVA实现验证码主要的代码部分,生成图片以及代码_第1张图片
代码如下:

package cn.itcast.servelt;


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

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        int length=200;
        int height=100;

        //1.创建一对象,验证码图片对象
        BufferedImage image = new BufferedImage(length, height, BufferedImage.TYPE_INT_RGB);
        //2.美化图片,填充背景色
        Graphics gra = image.getGraphics();
        //设置背景填充颜色
        gra.setColor(Color.black);//设置填充颜色
        gra.fillRect(0,length,0,height);//设置填充范围
        //设置字体、加粗、斜体、大小
        gra.setFont(new Font("宋体",Font.BOLD|Font.ITALIC,40));
        //设置字体的随机颜色数组
        Color[] colors= new Color[]{Color.YELLOW, Color.pink,Color.BLUE,Color.GREEN,Color.white,Color.RED};
        //创建要出现的验证码字符串
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

        Random random = new Random();
        for (int i = 1; i <=4; i++) {
            //生成随机角标索引
            int index = random.nextInt(str.length());
            //获取随机字符
            char c = str.charAt(index);
            //设置随机字符的字体随机颜色
            gra.setColor(colors[random.nextInt(colors.length)]);
            //写验证码,以及验证码应该出现的位置
            gra.drawString(c+" ",length/5*i,height/2);
        }
        //画5条干扰线,防止被别人破解
        for (int i = 1; i <=5 ; i++) {
            //随机生成x1点和x2点的横坐标位置
            int x1 = random.nextInt(length);
            int x2 = random.nextInt(length);
            //随机生成y1点和y2点的纵坐标位置
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);

            //画干扰线,设置随机颜色
            gra.setColor(colors[random.nextInt(colors.length)]);
            gra.drawLine(x1,y1,x2,y2);
        }
        //将图片输出到页面展示
        ImageIO.write(image,"jpg",response.getOutputStream());

    }

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

转载注明出处,拿去不谢!半成品仍需同志们继续完善。

你可能感兴趣的:(JAVA)