How to merge images

How to merge images

         You need to calculate the total size of the resulting image before merging. You can merge images in the horizontal or vertical direction. Depending on the merge direction, you will need to sum the total width or total height of the new images. Then create a new merge image with the calculated dimensions and put the images into the new one.

import com.aspose.imaging.*;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.sources.FileCreateSource;
String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
String outputPath = "output-horizontal.jpg";
String tempFilePath = "temp.jpg";
// Getting resulting image size.
int newWidth = 0;
int newHeight = 0;
for (String imagePath : imagePaths)
{
try (RasterImage image = (RasterImage) Image.load(imagePath))
{
Size size = image.getSize();
newWidth += size.getWidth();
newHeight = Math.max(newHeight, size.getHeight());
}
}
// Combining images into new one.
try (JpegOptions options = new JpegOptions())
{
Source tempFileSource = new FileCreateSource(tempFilePath, true);
options.setSource(tempFileSource);
options.setQuality(100);
try (JpegImage newImage = (JpegImage) Image.create(options, newWidth, newHeight))
{
int stitchedWidth = 0;
for (String imagePath : imagePaths)
{
try(RasterImage image = (RasterImage) Image.load(imagePath))
{
Rectangle bounds = new Rectangle(stitchedWidth, 0, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedWidth += image.getWidth();
}
}
newImage.save(outputPath);
}
}

You can find more Java code examples in the Aspose.Imaging documentation article Merge images.