Merge JPG Images in C# – .NET Imaging API

Sometimes we have a need to create an image by combining several JPG images together. This article explains how to do this in C#.

C# Imaging API – Free Download

Aspose.Imaging for .NET provides a number of flexible routines for creating and manipulating images within .NET applications. It lets you combine JPG files in a few lines of code. You can either get it installed within your .NET application using NuGet or download API’s DLL.

Install-Package Aspose.Imaging

Merge JPG Images Horizontally in C#

The following are the steps to merge JPEG images horizontally in C#.

  • Create an array of JPEG images you want to merge.
  • Compute the width of the resulting image by adding the width of all images in the array and height by finding the maximum height of an image in the array.
  • Create a new image using JpegImage class and set its width and height to the one computed in the last step.
  • Iterate over the array of images (you want to merge) and perform the following tasks on each image:
    • Load pixels of an image using LoadArgb32Pixels method and save them in the resulting image using SaveArgb32Pixels method. This method also takes a Rectangle object as an argument that defines the position of an image in the resulting image.
  • Save the resulting image as a JPEG image.

The following code sample shows how to join JPEG images horizontally in C#.

Input Images

First Image
Second Image

Output Image

Horizontally Merged Image

Merge JPG Images Vertically in C#

The steps to merge JPEG images vertically are same as above. A little difference is that we compute the height of the resulting image by adding the height of all images in the array and width by finding the maximum width of an image in the array. The following code sample shows how to join JPEG images vertically in C#.

Vertically Merged Image

Merge JPG Images into PDF in C#

You may have a need to combine the JPEG images into PDF. You can do this by just making a minor change in the Image.Save method (use .pdf extension instead of .jpg).

Merge JPG Images into PNG in C#

Similarly, you may want to combine the JPEG images into PNG. As shown above, you just need to use .png extension instead of .jpg in the Image.Save method.

Conclusion

In this article, you learnt how to join JPEG images in C#. You can either combine them horizontally or vertically. You also learnt how to save the merged image as PDF or PNG. For more information, please check the documentation of Aspose.Imaging for .NET. If you have any question, please feel free to contact us at our Support Forum.

See Also