代码改变世界

Java 生成海报

2021-05-24 16:13  taozsay  阅读(407)  评论(0编辑  收藏  举报

最近项目有个功能是生成海报

一个背景图片,一个二维码图片

将两个图片合并成一个图片。

写了一个工具类,需要的朋友自取。

 

 1 @Component
 2 public class PictureUtil {
 3     /**
 4      * @param file1Src 在线图片地址1
 5      * @param file2Src 在线图片地址2
 6      * @param response
 7      * @param x
 8      * @param y
 9      */
10     public void composePic(String file1Src, String file2Src, Integer x, Integer y, HttpServletResponse response) {
11         try {
12             java.net.URL url = new java.net.URL(file1Src);
13             URLConnection conn = url.openConnection();
14             InputStream bgFile = conn.getInputStream();
15             Image bgSrc = javax.imageio.ImageIO.read(bgFile);
16 
17             url = new java.net.URL(file2Src);
18             conn = url.openConnection();
19             InputStream logoFile = conn.getInputStream();
20             Image logoSrc = javax.imageio.ImageIO.read(logoFile);
21 
22             int bgWidth = bgSrc.getWidth(null);
23             int bgHeight = bgSrc.getHeight(null);
24             int logoWidth = logoSrc.getWidth(null);
25             int logoHeight = logoSrc.getHeight(null);
26 
27             BufferedImage tag = new BufferedImage(bgWidth, bgHeight, BufferedImage.TYPE_INT_RGB);
28 
29             Graphics2D g2d = tag.createGraphics();
30             g2d.drawImage(bgSrc, 0, 0, bgWidth, bgHeight, null);
31             g2d.drawImage(logoSrc, x, y, logoWidth, logoHeight, null);
32 
33             ImageIO.write(tag, "png", response.getOutputStream());
34         } catch (Exception e) {
35             e.printStackTrace();
36         }
37     }
38 }

 

参考:

Java后台通过IO流将文件返回至前端进行预览