说明
横向拼接,图片高度要一致
纵向拼接,图片宽度要一致
代码
package org.example;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author ali
*/
public class MergeImage {
public static void test(List<String> paths, boolean isHorizontal, String targetFile) throws IOException {
// 图片
List<BufferedImage> pics = new ArrayList<>();
for (String path : paths) {
pics.add(ImageIO.read(new File(path)));
}
// 计算宽高
int newWidth = isHorizontal ? pics.stream().mapToInt(BufferedImage::getWidth).sum() : pics.get(0).getWidth();
int newHeight = isHorizontal ? pics.get(0).getHeight() : pics.stream().mapToInt(BufferedImage::getHeight).sum();
// 图片处理
BufferedImage imageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
AtomicInteger pixelPointsWidth = new AtomicInteger();
AtomicInteger pixelPointsHeight = new AtomicInteger();
pics.forEach(v -> {
int width = v.getWidth();
int height = v.getHeight();
int[] image = new int[width * height];
image = v.getRGB(0, 0, width, height, image, 0, width);
if (isHorizontal) {
imageNew.setRGB(pixelPointsWidth.get(), 0, width, newHeight, image, 0, width);
pixelPointsWidth.addAndGet(width);
} else {
imageNew.setRGB(0, pixelPointsHeight.get(), newWidth, height, image, 0, newWidth);
pixelPointsHeight.addAndGet(height);
}
});
// 图片生成
try {
ImageIO.write(imageNew, targetFile.split("\\.")[1], new File(targetFile));
System.out.println("生成成功");
} catch (IOException e) {
System.out.println("生成失败:" + e.getMessage());
}
}
}
测试
/**
* 图片横向拼接
*/
public void testHorizontalApp() throws IOException {
MergeImage.test(Arrays.asList(
"/Users/test/Downloads/1",
"/Users/test/Downloads/2",
"/Users/test/Downloads/3",
"/Users/test/Downloads/4"
), true, "/Users/test/Downloads/" + System.currentTimeMillis() + ".jpeg");
}
/**
* 图片纵向拼接
*/
public void testVerticalApp() throws IOException {
MergeImage.test(Arrays.asList(
"/Users/test/Downloads/1",
"/Users/test/Downloads/2",
"/Users/test/Downloads/3",
"/Users/test/Downloads/4"
), false, "/Users/test/Downloads/" + System.currentTimeMillis() + ".jpeg");
}