Skip to content

Instantly share code, notes, and snippets.

@aspose-com-kb
Last active September 3, 2023 04:51
How to Merge Photos in Java. For more details: https://kb.aspose.com/imaging/java/how-to-merge-photos-in-java/
import com.aspose.imaging.*;
public class Main {
public static void main(String[] args) throws Exception // Merge photos in Java
{
// Set the licenses
new License().setLicense("License.lic");
// Creating an array of strings
String[] imagePaths = new String[3];
// Initializing array elements
imagePaths[0] = "Sample1.jpg";
imagePaths[1] = "Sample2.jpg";
imagePaths[2] = "Sample3.jpg";
// Path of output image
String outputPath = "output-combine.jpg";
// Get resulting image size
int newWidth = 0;
int newHeight = 0;
for (String imagePath : imagePaths) {
try (com.aspose.imaging.RasterImage image = (com.aspose.imaging.RasterImage) com.aspose.imaging.Image.load(imagePath)) {
com.aspose.imaging.Size size = image.getSize();
newWidth = Math.max(newWidth, size.getWidth());
newHeight += size.getHeight();
}
}
// Combine images into new one
try (com.aspose.imaging.imageoptions.JpegOptions options = new com.aspose.imaging.imageoptions.JpegOptions()) {
options.setSource(new com.aspose.imaging.sources.StreamSource()); // empty
options.setQuality(100);
// Create resultant image
try (com.aspose.imaging.fileformats.jpeg.JpegImage newImage = (com.aspose.imaging.fileformats.jpeg.JpegImage) com.aspose.imaging.Image.create(options, newWidth, newHeight)) {
int stitchedHeight = 0;
for (String imagePath : imagePaths) {
try (com.aspose.imaging.RasterImage image = (com.aspose.imaging.RasterImage) com.aspose.imaging.Image.load(imagePath)) {
com.aspose.imaging.Rectangle bounds = new com.aspose.imaging.Rectangle(0, stitchedHeight, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedHeight += image.getHeight();
}
}
// Save resultant image
newImage.save(outputPath);
}
}
System.out.println("Done");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment