package com.ruoyi.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ImageMerge {
    public static void main(String[] args) throws Exception {
        // 加载第一张图片
        BufferedImage image1 = ImageIO.read(new File("G:\\download\\output.png"));
        // 加载第二张图片
        BufferedImage image2 = ImageIO.read(new File("G:\\download\\output2.png"));

        List<String> list = new ArrayList<>();
        list.add("G:\\download\\output.png");
        list.add("G:\\download\\output2.png");
        list.add("G:\\download\\output3.png");

        mergeImages(list,null);
    }


    public static void mergeImages(List<String> imagePathList,String outputPath) throws Exception {
        // 加载第一张图片
        BufferedImage image1 = ImageIO.read(new File(imagePathList.get(0)));

        Integer height = image1.getHeight();
        Integer width = image1.getWidth();

        for (int i = 0; i < imagePathList.size(); i++) {
            if (i == 0) {
                continue;
            }
            BufferedImage image = ImageIO.read(new File(imagePathList.get(i)));
            height = height + image.getHeight();
        }
        // 创建一个新的图片用于合并
        BufferedImage combinedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        // 合并第一张图片
        Integer heightTemp = 0;
        Graphics2D g = null;
        for (int i = 0; i < imagePathList.size(); i++) {
            BufferedImage image = ImageIO.read(new File(imagePathList.get(i)));
            g = combinedImage.createGraphics();
            if (i == 0) {
                g.drawImage(image, 0, heightTemp, null);

            } else {
                g.drawImage(image, 0, heightTemp, null);
            }
            heightTemp = heightTemp + image.getHeight();
            // 释放图形上下文
            g.dispose();
        }
        // 保存合并后的图片
        ImageIO.write(combinedImage, "PNG", new File(outputPath));
    }
}