Combine several images to form a single image using C#

August 31st, 2012 | Posted by Nitesh Luharuka in .Net | Utility

Friends,

Today, I was working on a problem where I required to add up two image to form a single image. The following code does the same for you.

1. Place a button from the toolbar on your C# form.
2. Select the button and press F4.
3. Change the name to cmdCombine and text as Combine Images.
4. Double click on the button to generate its click handler as follows:

private void cmdCombine _Click(object sender, EventArgs e)
{
}
5. Place the following code in the event handler block.
//Change the path to location where your images are stored.
DirectoryInfo directory=new DirectoryInfo("C:\\MyImages");
if(directory!=null)
{
FileInfo[]files = directory.GetFiles();
CombineImages(files);
}

6. Write the following code after the event handler block.

private void CombineImages(FileInfo[] files)
{
//change the location to store the final image.
string finalImage = @"C:\\MyImages\\FinalImage.jpg";
List imageHeights = new List();
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();
imageLocation.Image = Image.FromFile(finalImage);
}

You need to include the System.Drawing.Imaging namespace to make this code work.

Please change the directory path where your images are stored and where you want to generate the final image.

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

6 Responses



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Support us!

If you like this site please help and make click on any of these buttons!

×