• 【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 page</title>
    </head>
    <body>
        <h1>祝福大家虎年如虎添翼.</h1>
        <img src="../happynewyearPic"/>
    </body>
    </html>

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

    看确实简单吧。

    END

  • 相关阅读:
    hdu4990矩阵快速幂
    预处理+状态压缩+剪枝——codefoece 1209E
    AC自动机处理多串匹配——cf1202E
    二维差分前缀和——cf1202D(好题)
    序列递推——cf1204E(好题)
    建模+线性dp——cf1201D
    暴力——cf1202C
    经典排序背包——cf1203F
    思维+贪心——cf1042D
    分块——cf1207F
  • 原文地址:https://www.cnblogs.com/heyang78/p/15861240.html
Copyright © 2020-2023  润新知