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.
- Place a button from the toolbar on your C# form.
- Select the button and press F4.
- Change the name to
cmdCombine
and text as Combine Images. - Double click on the button to generate its click handler as follows:
private void cmdCombine _Click(object sender, EventArgs e)
{
}
- Place the following code in the event handler block.
DirectoryInfo directory=new DirectoryInfo("C:\\MyImages");
if(directory!=null)
{
FileInfo[]files = directory.GetFiles();
CombineImages(files);
}
- Write the following code after the event handler block.
private void CombineImages(FileInfo[] files)
{
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.