JavaWeb-Servlet-通过servlet生成验证码图片

package cn.edu.mju.project2.comtroller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("captcha")
public class CaptcheController extends HttpServlet {
    private  final  int WIDTH=120;//生成图片的宽度
    private  final int WEIGHT=30;//生成图片的高度
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedImage img=new BufferedImage(WIDTH,WEIGHT,BufferedImage.TYPE_INT_RGB);//在内存中创建一张图片
        //得到图片
        Graphics g=img.getGraphics();
        //设置验证码背景为白色
        g.setColor(Color.WHITE);
        //设置验证码背景图片格式
        g.fillRect(0,0,WIDTH,WEIGHT);
        //设置验证码格式
        g.setFont(new Font("宋体",Font.BOLD,28));
        //在图片上画上干扰线
        drawRandomLine(g);
        //放上4个随机字符
        String code=randomString((Graphics2D)g,4);
        //设置验证码在图片上位置
        g.drawString(code,20,30);
        g.dispose();
        //把图片传给浏览器
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(img,"JPEG",out);
        try {
            out.flush();
        }catch (Exception e){
        }finally {
            out.close();
        }
    }
    /*
     * 在图片上画随机线条
     *
     * */
    private void drawRandomLine(Graphics g) {
        //设置颜色
        g.setColor(Color.black);
        //设置线条个数并画线
        for ( int i = 0 ; i < 3 ; i++ ) {
            int x1 = new Random().nextInt(WIDTH);
            int y1 = new Random().nextInt(WEIGHT);
            int x2 = new Random().nextInt(WIDTH);
            int y2 = new Random().nextInt(WEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
    }
    /*创建随机字符
    *
    * */
    public String randomString(Graphics2D g,int count){
        StringBuilder builder=new StringBuilder();
        String source="abcdefghijklmnpqrstuvwxy0123456789";//这个去除容易混淆的o和z两个字母
        int x=5;
        Random rnd=new Random();
        for(int i=0;i<count;i++){
            int pos= rnd.nextInt(source.length());
            String s=source.substring(pos,pos+1);
            //设置字体的旋转角度
            int degree = new Random().nextInt() % 30;
            //正向角度
            g.rotate(degree  * Math.PI / 180 , x,20);
            g.drawString(s, x, 20);
            //反向角度
            g.rotate(-degree  * Math.PI / 180 , x,20);
            x+=30;
        }
        return builder.toString();
    }
}

运行结果:
在这里插入图片描述
在这里插入图片描述

你可能感兴趣的:(servlet)