java如何拼接照片
使用Java拼接照片的方法
使用BufferedImage和Graphics2D
加载需要拼接的图片,创建新的BufferedImage对象作为画布,使用Graphics2D将图片绘制到画布上。
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageConcat {
public static void concatImages(String[] imagePaths, String outputPath, boolean horizontal) throws Exception {
BufferedImage[] images = new BufferedImage[imagePaths.length];
int totalWidth = 0;
int totalHeight = 0;
for (int i = 0; i < images.length; i++) {
images[i] = ImageIO.read(new File(imagePaths[i]));
if (horizontal) {
totalWidth += images[i].getWidth();
totalHeight = Math.max(totalHeight, images[i].getHeight());
} else {
totalHeight += images[i].getHeight();
totalWidth = Math.max(totalWidth, images[i].getWidth());
}
}
BufferedImage combined = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = combined.createGraphics();
int currentX = 0;
int currentY = 0;
for (BufferedImage image : images) {
g.drawImage(image, currentX, currentY, null);
if (horizontal) {
currentX += image.getWidth();
} else {
currentY += image.getHeight();
}
}
g.dispose();
ImageIO.write(combined, "jpg", new File(outputPath));
}
}
使用第三方库Thumbnailator
Thumbnailator库提供了更简洁的API来处理图片拼接。
import net.coobird.thumbnailator.Thumbnails;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class ThumbnailatorConcat {
public static void concatImages(List<File> images, File output, boolean horizontal) throws Exception {
if (horizontal) {
Thumbnails.of(images)
.size(640, 480)
.outputQuality(1.0)
.toFiles(output);
} else {
Thumbnails.of(images)
.size(640, 480)
.outputQuality(1.0)
.toFiles(output);
}
}
}
处理不同尺寸的图片
当需要拼接不同尺寸的图片时,可以先将图片调整为相同高度或宽度。
public static void resizeAndConcat(String[] imagePaths, String outputPath, int targetWidth, int targetHeight) throws Exception {
BufferedImage[] resizedImages = new BufferedImage[imagePaths.length];
for (int i = 0; i < imagePaths.length; i++) {
BufferedImage original = ImageIO.read(new File(imagePaths[i]));
BufferedImage resized = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resized.createGraphics();
g.drawImage(original, 0, 0, targetWidth, targetHeight, null);
g.dispose();
resizedImages[i] = resized;
}
concatImages(resizedImages, outputPath, true);
}
注意事项
图片格式需要保持一致,避免混合不同格式导致问题。处理大图片时注意内存消耗,可能需要分块处理。输出路径需要确保有写入权限。

以上方法可以根据实际需求选择使用,第一种方法提供了最大的灵活性,第二种方法代码更简洁,第三种方法解决了尺寸不一致的问题。






