Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active August 10, 2021 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/9e4c397cef74dcfed71b8338f76b6aa1 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/9e4c397cef74dcfed71b8338f76b6aa1 to your computer and use it in GitHub Desktop.
Merge Multiple Images using C#
// Create list of images
string[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.JPG", "image5.png" };
// To create a temporary image
string tempFilePath = "temp.jpg";
// Get resulting image's size
List <Size> imageSizes = new List<Size>();
foreach (string imagePath in imagePaths)
{
using (RasterImage image = (RasterImage)Image.Load(imagePath))
{
imageSizes.Add(image.Size);
}
}
int newWidth = imageSizes.Sum(size => size.Width);
int newHeight = imageSizes.Max(size => size.Height);
// Combine images into new one
Source tempFileSource = new FileCreateSource(tempFilePath, isTemporal: true);
// Create jpeg options
JpegOptions options = new JpegOptions() { Source = tempFileSource, Quality = 100 };
using (JpegImage newImage = (JpegImage)Image.Create(options, newWidth, newHeight))
{
int stitchedWidth = 0;
// Merge images
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;
}
}
// Save the merged image
newImage.Save(outputPath);
}
// Create a list of images
string[] imagePaths = { "image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.png" };
// Get resulting image's size
List<Size> imageSizes = new List<Size>();
foreach (string imagePath in imagePaths)
{
using (RasterImage image = (RasterImage)Image.Load(imagePath))
{
imageSizes.Add(image.Size);
}
}
int newWidth = imageSizes.Max(size => size.Width);
int newHeight = imageSizes.Sum(size => size.Height);
// Combine images into new one
using (MemoryStream memoryStream = new MemoryStream())
{
// Create output source
StreamSource outputStreamSource = new StreamSource(memoryStream);
// Create jpeg options
JpegOptions options = new JpegOptions() { Source = outputStreamSource, Quality = 100 };
// Create output image
using (JpegImage newImage = (JpegImage)Image.Create(options, newWidth, newHeight))
{
int stitchedHeight = 0;
// Merge images
foreach (string imagePath in imagePaths)
{
using (RasterImage image = (RasterImage)Image.Load(imagePath))
{
Rectangle bounds = new Rectangle(0, stitchedHeight, image.Width, image.Height);
newImage.SaveArgb32Pixels(bounds, image.LoadArgb32Pixels(image.Bounds));
stitchedHeight += image.Height;
}
}
// Save the merged image
newImage.Save("merged-image.jpg");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment