【SpringBoot】如何在网页上显示AWT动态生成的图片


SpringBoot程序里,显示静态图片不是事,显示Canvas图也有固定套路,如果是用AWT生成的图片呢,也只是多两个步骤而已。

首先,我们需要准备一个对外服务的函数:

@RequestMapping("/happynewyearPic")
    public void showPicture(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("image/jpeg");//声明文件格式
        
        final int W=200;
        final int H=160;
        BufferedImage img=new BufferedImage(W,H,BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d=(Graphics2D)img.getGraphics();
        
        // 消除线条锯齿  
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
        
        // 填充矩形
        g2d.setColor(Color.red);
        g2d.fillRect(0, 0, W, H);
        
        // 绘直线
        g2d.setColor(Color.yellow);
        g2d.setStroke(new BasicStroke(2.0f));
        g2d.drawLine(20, H/2+10, W-20, H/2+10);
        
        // 绘文字
        g2d.setFont(new Font("宋体",Font.BOLD,24));
        g2d.drawString("2022新年快乐",26, H/2);
        
        g2d.dispose();// g2d使命完成
        
        
        ImageIO.write(img,"JPEG",response.getOutputStream());  
        PrintWriter out = response.getWriter();  
        out.flush();  
        out.close();  
    }

上面代码中,粗体文字是绘图,其余代码是固定范式代码。

之后,在页面上写一个img标签,其src指向函数所在地址:

DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Sample pagetitle>
head>
<body>
    <h1>祝福大家虎年如虎添翼.h1>
    happynewyearPic"/>
body>
html>

然后把页面跑起来就行了,效果如下:

看确实简单吧。

END

相关