How to Combine Images in C#
By FoxLearn 12/26/2024 8:23:53 AM 107
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);
- String to Byte Array Conversion in C#
- How to Trim a UTF-8 string to the specified number of bytes in C#
- How to Save a list of strings to a file in C#
- How to Convert string list to int list in C#
- How to Convert string list to float list in C#
- How to Remove a list of characters from a string in C#
- How to Check if a string contains any substring from a list in C#
- Find a character in a string in C#