How to merge JPG to JPG programmatically

Compose horizontal layout

Aspose.Imaging allows to process JPG to JPG merge programmatically using Aspose.Imaging API. Below example shows how to perform JPG to JPG horizontal merge

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);
}
}

Compose vertical layout

Below example shows how to perform JPG to JPG vertical merge

import com.aspose.imaging.Image;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.Rectangle;
import com.aspose.imaging.Size;
import com.aspose.imaging.fileformats.jpeg.JpegImage;
import com.aspose.imaging.imageoptions.JpegOptions;
import com.aspose.imaging.sources.StreamSource;
String[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
String outputPath = "output-vertical.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 = Math.max(newWidth, size.getWidth());
newHeight += size.getHeight();
}
}
// Combining images into new one.
try (JpegOptions options = new JpegOptions())
{
options.setSource(new StreamSource()); // empty
options.setQuality(100);
try (JpegImage newImage = (JpegImage) Image.create(options, newWidth, newHeight))
{
int stitchedHeight = 0;
for (String imagePath : imagePaths)
{
try(RasterImage image = (RasterImage) Image.load(imagePath))
{
Rectangle bounds = new Rectangle(0, stitchedHeight, image.getWidth(), image.getHeight());
newImage.saveArgb32Pixels(bounds, image.loadArgb32Pixels(image.getBounds()));
stitchedHeight += image.getHeight();
}
}
newImage.save(outputPath);
}
}