废话不多说,直接上代码,相关注释都在代码里给了注释了,还有不清楚的可以自己查一下,毕竟比较简单嘛

    public void generate(HttpServletResponse response,HttpSession session){
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        String code = drawImg(output);
        
    //    Subject currentUser = SecurityUtils.getSubject();  
        //Session session = currentUser.getSession();
        session.setAttribute(Const.SESSION_SECURITY_CODE, code);
        try {
            ServletOutputStream out = response.getOutputStream();
            //将此字节数组输出流的全部内容写入到指定的输出流参数中。
            output.writeTo(out);
            out.close();
        } catch (IOException e) {
            //e.printStackTrace();
        }
    }
    
    private String drawImg(ByteArrayOutputStream output){
        String code = "";
        for(int i=0; i<4; i++){
            code += randomChar();
        }
        int width = 70;
        int height = 25;
        //设置图片的宽度,高度,以及类型
        BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //设置所显示的字体
        Font font = new Font("Times New Roman",Font.PLAIN,20);
        //创建一个Graphics2D,可用于绘制到BufferedImage
        Graphics2D g = bi.createGraphics();
        g.setFont(font); //将字体设置进去
        Color color = new Color(66,2,82);  //设置颜色
        g.setColor(color);
        g.setBackground(new Color(226,226,240));  //设置背景颜色
        g.clearRect(0, 0, width, height);
        FontRenderContext context = g.getFontRenderContext();  //将其以文本显示
        Rectangle2D bounds = font.getStringBounds(code, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = y - ascent;
        g.drawString(code, (int)x, (int)baseY);  //输出图片的内容以及高度和宽度
        g.dispose();
        try {
            ImageIO.write(bi, "jpg", output);
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return code;
    }
    
    private char randomChar(){
        Random r = new Random();
        String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
        return s.charAt(r.nextInt(s.length()));
    }