Introduction
This trick will help you to merge two or more images (.jpg/.tiff/.png) into one image (.jpg/.tiff/.png).
Background
In one of my project scenarios, there is a need to combine 2 images into one image for further document processing. (For example: suppose my invoice of number #123 (2 page invoice) gets divided into 2 different pages and here I want to combine these pages into one for next level processing.
Using the Code
Here, you have to add reference for:
using System.Drawing;
using System.Drawing.Imaging; using System.IO;
In this example, I tried to Merge two "TIFF" files into one "TIFF". For example: Merge "1.tif" (2 pages) with "2.tif" (1 page) and make this 3 pager image as "1.tif". You can try for .Jpg, .Png, etc. image types.
localTaskSourceFile
and localTaskToFile
are physical path of files on local machine.
private void button1_Click(object sender, EventArgs e)
{
try
{
string From_Document_ImagePath = "C:\\1.tif";
string To_Document_ImagePath = "C:\\2.tif";
MergeDocument(From_Document_ImagePath, To_Document_ImagePath);
}
catch (Exception ex)
{
throw;
}
}
public void MergeDocument(string localTaskSourceFile, string localTaskToFile)
{
try
{
string FilePath = Path.GetDirectoryName(localTaskSourceFile);
string NewFile = Path.Combine(FilePath, Guid.NewGuid().ToString() + ".tif");
System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.SaveFlag;
ImageCodecInfo CodecInfo =
ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
EncoderParameters EncoderParameters = new EncoderParameters(1);
Bitmap FromImage = (Bitmap)Image.FromFile(localTaskSourceFile);
Bitmap currentToImage = (Bitmap)Image.FromFile(localTaskToFile);
int Frompages = FromImage.GetFrameCount(FrameDimension.Page);
int Topages = currentToImage.GetFrameCount(FrameDimension.Page);
EncoderParameters.Param[0] =
new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
FromImage.Save(NewFile, CodecInfo, EncoderParameters);
for (int counter = 1; counter < Frompages; counter++)
{
FromImage.SelectActiveFrame(FrameDimension.Page, counter);
EncoderParameters.Param[0] =
new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);
FromImage.SaveAdd(FromImage, EncoderParameters);
}
for (int counter = 0; counter < Topages; counter++)
{
currentToImage.SelectActiveFrame(FrameDimension.Page, counter);
EncoderParameters.Param[0] =
new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);
FromImage.SaveAdd(currentToImage, EncoderParameters);
}
FromImage.Dispose();
currentToImage.Dispose();
FromImage = null;
currentToImage = null;
File.Delete(localTaskSourceFile);
File.Move(NewFile, localTaskSourceFile);
File.Delete(NewFile);
}
catch (Exception ex)
{
throw;
}
}
Hope this article is useful to you!
Points of Interest
I have combined 2 images into one Image. You can try for different image types.
History
- 25th November, 2016: Initial version