How to append mulitpage TIFF images to an output file, using C# with VS2010?

I am writing a C# console application using VS2010 to generate 2 records at a time into multipage TIFF images.

The variable "img" contains the front image of a check.

The variable "img2" contains the back image of a check.

Function A is performed for each pair of front and back images of each check processed from an input file:

Funtion A
{

   Byte[] img =  bytes.Skip(irecpositionrevised + irectypelength).Take(intpos1revised).ToArray();

   Byte[] img1 = bytes.Skip(irecpositionrevised + irectypelength + intpos1revised).Take(intpos2revised).ToArray();

   newImage[CheckOrderNum - 1] = MergeTwoImages(ConvertFromByteArray(img), ConvertFromByteArray(img1));
}


After all checks have been read & processed via Function A, the following foreach loop is performed to write out
ALL multipage TIFF images:

foreach (Image image in newImage)
{
    image.Save("L:\\F\\Source\\test1.tiff", System.Drawing.Imaging.ImageFormat.Tiff);                
}  

When I run my application, it appears that the test1.tiff file ONLY contains the last multipage TIFF Image processed.

My goal is to write out ALL mulitpage TIFF Images to a file titled test1.tiff, so that I can see the front image & back image
of ALL checks my application reads from an input file.

Is my program APPENDING ALL mulitpage TIFF images to the test1.tiff file
OR is my program OVERWRITING the existing TIFF multipage Image with the current TIFF mulitpage read in?

If I am overwriting each record, could you tell me how to resolve this error so that the application will append the current record to the existing records?




private static Image ConvertFromByteArray(byte[] input)
{
    using (var ms = new MemoryStream(input))
    {
        return Image.FromStream(ms);
    }
}

public static  Bitmap MergeTwoImages(Image firstImage, Image secondImage)
{
    if (firstImage == null)
    {
        throw new ArgumentNullException("firstImage");
    }

    if (secondImage == null)
    {
        throw new ArgumentNullException("secondImage");
    }

    int outputImageWidth = firstImage.Width > secondImage.Width ? firstImage.Width : secondImage.Width;

    int outputImageHeight = firstImage.Height + secondImage.Height + 1;

    Bitmap outputImage = new Bitmap(outputImageWidth, outputImageHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    using (Graphics graphics = Graphics.FromImage(outputImage))
    {
        graphics.DrawImage(firstImage, new Rectangle(new Point(), firstImage.Size),
            new Rectangle(new Point(), firstImage.Size), GraphicsUnit.Pixel);
        graphics.DrawImage(secondImage, new Rectangle(new Point(0, firstImage.Height + 1), secondImage.Size),
                    new Rectangle(new Point(), secondImage.Size), GraphicsUnit.Pixel);
    }
                       
    return outputImage;
}
zimmer9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

KimputerCommented:
I think you should take a look at the code here: http://www.vbdotnetforums.com/graphics-gdi/22113-create-multipage-tiff-loop.html
While it's vb.net, I'm pretty sure you can figure out the C# syntax.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
Here is one way you could accomplish this:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace EE_Q28711383
{
	class Program
	{
		static void Main(string[] args)
		{
			List<Image> images = new List<Image>();
			images.Add(Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "image1.jpg")));
			images.Add(Image.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "image2.jpg")));
			images.MergeImages(new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "image3.tiff")));
		}
	}

	static class Extensions
	{
		public static void MergeImages(this IEnumerable<Image> images, string fileName)
		{
			images.MergeImages(new FileInfo(fileName));
		}

		public static void MergeImages(this IEnumerable<Image> images, FileInfo file)
		{
			if (images == null)
				throw new ArgumentNullException("images", "Images cannot be null");

			if (file == null)
				throw new ArgumentNullException("file", "File cannot be null");

			ImageCodecInfo codec = null;
			Image tiff = null;
			MemoryStream stream = null;
			EncoderParameters parameters = null;
			try
			{
				codec = (from _codec in ImageCodecInfo.GetImageEncoders() where _codec.MimeType.Equals("image/tiff", StringComparison.OrdinalIgnoreCase) select _codec).FirstOrDefault();
				if (codec != default(ImageCodecInfo))
				{
					bool first = true;
					parameters = new EncoderParameters(2);
					parameters.Param[0] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionCCITT4);
					parameters.Param[1] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame);

					foreach (Image image in images)
					{
						stream = new MemoryStream();
						image.Save(stream, ImageFormat.Tiff);

						if (first)
						{
							tiff = Image.FromStream(stream);
							tiff.Save(file.FullName, codec, parameters);
							first = false;
						}
						else
						{
							parameters.Param[1] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage);
							tiff.SaveAdd(Image.FromStream(stream), parameters);
						}
						stream.Dispose();
						image.Dispose();
					}

					parameters.Param[1] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.Flush);
					tiff.SaveAdd(parameters);
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("Exception reported: {0}", ex);
			}
			finally
			{
				parameters.Dispose();
				stream.Dispose();
				tiff.Dispose();
			}
		}
	}
}

Open in new window

-saige-
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.