A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 星空下第一高手 初级黑马   /  2019-9-12 15:35  /  921 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package itvast.Servlet;

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;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/ckeckCodeDemo01")
public class CheckCodeDemo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //设置编码格式
        //response.setContentType("charset=utf-8");
        int wight = 100;
        int height = 50;
       //创建一个对象,在内存中图片
        BufferedImage img = new BufferedImage(wight,height,BufferedImage.TYPE_3BYTE_BGR);

        //美化图片
        Graphics g = img.getGraphics();
        g.setColor(Color.PINK);
        g.fillRect(0,0,wight,height);
        g.setColor(Color.BLUE);
        g.drawRect(0,0,wight-1,height-1);
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random ran = new Random();
        StringBuilder sb = new StringBuilder();
        for(int i = 1; i <= 4; i++) {
            int a = ran.nextInt(str.length());
            char chr = str.charAt(a);
            sb.append(chr);
            g.drawString(chr+"",wight/5*i,height/2);
        }
        String checkCode_session = sb.toString();
        request.getSession().setAttribute("checkCode_session",checkCode_session);
        for(int i = 0; i <= 6; i++) {
            int x1 = ran.nextInt(wight);
            int x2 = ran.nextInt(wight);
            int y1 = ran.nextInt(height);
            int y2 = ran.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }


        //将图片输出到页面展示
        ImageIO.write(img,"jpg",response.getOutputStream());
    }

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

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马