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.
A passionate developer with over 10 years of experience and building my software company code by code. Experience withMS Technologies like .Net | MVC | Xamarin | Sharepoint | MS Project Server and PhP along with open source CMS Systems like Wordpress/DotNetNuke etc.
Love to debug problems and solve them. I love writing articles on my website in my spare time. Please visit my Website for more details and subscribe to get technology related tips/tricks. #SOreadytohelp