Skip to content

Instantly share code, notes, and snippets.

@sohail-aspose
Last active December 16, 2020 07:39
Show Gist options
  • Save sohail-aspose/9d8e34cf5e2d55b74d6ecbb6b4c6fac5 to your computer and use it in GitHub Desktop.
Save sohail-aspose/9d8e34cf5e2d55b74d6ecbb6b4c6fac5 to your computer and use it in GitHub Desktop.
Merge JPEG Images Horizontally in C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Aspose.Imaging;
using Aspose.Imaging.FileFormats.Jpeg;
using Aspose.Imaging.ImageOptions;
using Aspose.Imaging.Sources;
// Array of images you want to merge.
string[] imagePaths = { "Image1.jpeg", "Image2.jpg" };
// Name of the output/resulting file.
string outputPath = "MergeImages_Horizontally.jpg";
// Getting resulting image size.
List<Size> imageSizes = new List<Size>();
foreach (string imagePath in imagePaths)
{
using (RasterImage image = (RasterImage)Image.Load(imagePath))
{
imageSizes.Add(image.Size);
}
}
// Width and height of the resulting image
int newWidth = imageSizes.Sum(size => size.Width);
int newHeight = imageSizes.Max(size => size.Height);
// Merging images into one.
Source tempFileSource = new FileCreateSource("temp.jpg", isTemporal: true);
JpegOptions options = new JpegOptions() { Source = tempFileSource, Quality = 100 };
using (JpegImage newImage = (JpegImage)Image.Create(options, newWidth, newHeight))
{
int stitchedWidth = 0;
foreach (string imagePath in imagePaths)
{
using (RasterImage image = (RasterImage)Image.Load(imagePath))
{
Rectangle bounds = new Rectangle(stitchedWidth, 0, image.Width, image.Height);
newImage.SaveArgb32Pixels(bounds, image.LoadArgb32Pixels(image.Bounds));
stitchedWidth += image.Width;
}
}
newImage.Save(outputPath);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment