How to Combine Images in C#
By FoxLearn 12/26/2024 8:23:53 AM 83
This can be useful for creating collages or even preparing images for applications like Deep Zoom Composer, where importing images individually might be inefficient.
We'll start by loading the individual images into memory. For memory efficiency, this can be done one image at a time, but in our example, we will load all images at once for simplicity and speed.
public static System.Drawing.Bitmap CombineImages(string[] filePaths) { List<System.Drawing.Bitmap> images = new List<System.Drawing.Bitmap>(); System.Drawing.Bitmap finalImage = null; try { int totalWidth = 0; int maxHeight = 0; foreach (string filePath in filePaths) { System.Drawing.Bitmap image = new System.Drawing.Bitmap(filePath); totalWidth += image.Width; maxHeight = Math.Max(maxHeight, image.Height); images.Add(image); } finalImage = new System.Drawing.Bitmap(totalWidth, maxHeight); return finalImage; } catch (Exception ex) { if (finalImage != null) finalImage.Dispose(); throw ex; } finally { // Dispose of all Bitmap objects foreach (System.Drawing.Bitmap image in images) { image.Dispose(); } } }
Since Bitmap
objects use unmanaged resources, it’s important to dispose of them when done. We’ll use a try-finally
block to ensure proper cleanup, especially in case of exceptions.
Once the images are loaded and memory is managed, the next step is to actually draw them onto the finalImage
. The Graphics
object is used to manipulate and draw on the image. Each image is placed sequentially in the combined image, ensuring they don’t overlap.
// Get all the image files in a directory string[] filePaths = Directory.GetFiles(@"C:\NatureImages"); // Combine them into one image System.Drawing.Bitmap combinedImage = CombineImages(filePaths); // Save the final stitched image combinedImage.Save(@"C:\combinedNatureImage.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#