背景
最近有实现一个需求。会产生多张图片,这些图片的宽度一直,然后要进行拼接,拼接成一张长的图片返回。
代码实现
/**
* 图片合并
* 核心原理就是一个像素一个像素的进行RGB复制。
* @param piclist
* @return
*/
public static BufferedImage doImg(List<BufferedImage> piclist) {
if (piclist == null || piclist.size() <= 0) {
return null;
}
try {
int height = 0; // 总高度
int width = 0; // 总宽度
for (BufferedImage image : piclist) {
height = height + image.getHeight();
}
width = piclist.get(0).getWidth();
BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
int height_ = 0;
for (BufferedImage image : piclist) {
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
imageResult.setRGB(x, y + height_, image.getRGB(x, y));
}
}
height_ = height_ + image.getHeight();
}
return imageResult;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
File file1 = new File("D:/test/1.png");
BufferedImage image1 = ImageIO.read(file1);
File file2 = new File("D:/test/1.png");
BufferedImage image2 = ImageIO.read(file2);
File outFile = new File("D:/test/result.png");
List<BufferedImage> piclist = new ArrayList<>();
piclist.add(image1);
piclist.add(image2);
BufferedImage resultImage = doImg(piclist);
ImageIO.write(resultImage, "png", outFile);
}
补充需求
因为我是通过WORD产生PDF再转图片的,导致底部会有很大的一块白边,所以需要把这个白边去掉。所以需要添加一个去白边的方法
/**
* 底部截取白色
* 通过x,y坐标从下到上,如果该X轴上所有的点都是白色,就判断这一行需要截取,直到没有白色为止
* @param img
* @return
*/
public static int getHeight(BufferedImage img) {
int trimmedHeight = 0;
for (int y = img.getHeight() - 1; y >= 0; y--) {
boolean flag = true;
for (int x = 0; x < img.getWidth(); x++) {
if (img.getRGB(x, y) != Color.WHITE.getRGB()) {
flag = false;
break;
}
}
if (flag) {
trimmedHeight = trimmedHeight + 1;
} else {
break;
}
}
return trimmedHeight;
}
/**
* 顶部截取白色
* 通过x,y坐标从下到上,如果该X轴上所有的点都是白色,就判断这一行需要截取,直到没有白色为止
* @param img
* @return
*/
public static int getHeight2(BufferedImage img) {
int trimmedHeight = 0;
for (int y = 0; y < img.getHeight(); y++) {
boolean flag = true;
for (int x = 0; x < img.getWidth(); x++) {
if (img.getRGB(x, y) != Color.WHITE.getRGB()) {
flag = false;
break;
}
}
if (flag) {
trimmedHeight = trimmedHeight + 1;
} else {
break;
}
}
return trimmedHeight;
}
public static void main(String[] args) throws Exception {
File file1 = new File("D:/test/3.png");
BufferedImage image1 = ImageIO.read(file1);
File outFile = new File("D:/test/result.png");
int deleteBottomHeight = getHeight(image1);
int deleteTopHeight = getHeight2(image1);
image1 = image1.getSubimage(0, deleteTopHeight, image1.getWidth(), image1.getHeight() - deleteBottomHeight - deleteTopHeight);
ImageIO.write(image1, "png", outFile);
}