In this article, I have described how to display an array of images in single PictureBox using C#.
Normally users used multiple PictureBox for multiple images.
Before the solution, I have shown you an effect of multiple images into multiple picture boxes.
Figure 1:
Now, I going to describe, how to use multiple images into single PictureBox.
Step 1: Open a window form (e.g. Array of Image) in Visual Studio with C# and place one button (e.g. Display Image) and one PictureBox (e.g. pictureBox1) control as below image (e.g. Figure 2).
Figure 2:
Step 2: Use below namespace in your window form’s .cs file.
using System.Drawing;
using System.IO;
using System.Collections.Generic;
Step 3: Generate button click event and paste below the line of code
//Change the path to location where your images are stored.
DirectoryInfo directory = new DirectoryInfo(@'D:\ImageDemo\Images');
if (directory != null)
{
FileInfo[] files = directory.GetFiles();
CombineImages(files);
}
Note: In the above code, changed the existing path (e.g. D:\ImageDemo\Images) from your image path folder.
This folder should be possessing at least two images for better understanding and all images should be the same damnations.
Step 4: Place below the line of code outside of the button click event. This line of code converts images into a single image.
private void CombineImages(FileInfo[] files)
{
try
{
//change the location to store the final image.
string finalImage = @'D:\FinalImage\Flower.jpg';
List<int> imageHeights = new List<int>();
int nIndex = 0;
int width = 0;
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
}
imageHeights.Sort();
int height = imageHeights[imageHeights.Count - 1];
Bitmap img3 = new Bitmap(width, height);
Graphics g = Graphics.FromImage(img3);
g.Clear(SystemColors.AppWorkspace);
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (nIndex == 0)
{
g.DrawImage(img, new Point(0, 0));
nIndex++;
width = img.Width;
}
else
{
g.DrawImage(img, new Point(width, 0));
width += img.Width;
}
img.Dispose();
}
g.Dispose();
img3.Save(finalImage, System.Drawing.Imaging.ImageFormat.Jpeg);
img3.Dispose();
pictureBox1.Image = Image.FromFile(finalImage);
}
catch
{
}
}
Note: In the above code, replace the default path (e.g. D:\FinalImage\Flower.jpg) from where you want to save a dynamically generated images.
This path will be different from the image sources path which we have given in step 3.
Step 5: Save your application and execute it. Click on the button “Display Image” and see an output as below.
mithun Ruwan
hi if you can please help me to use this method for webcam video capturing in c#, thanks