【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

posted @   逆火狂飙  阅读(226)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2020-02-03 索引对单表查询的影响(Cost和consistent gets)
2020-02-03 【Oracle】个人收集整理的Oracle常用SQL及命令
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东
点击右上角即可分享
微信分享提示