Convert different picture formats (jpg, gif, png, etc.) to TIFF format

Viewed 43648

I am working on reading text from an image through OCR. It only supports TIFF format images.

So, I need to convert other formats to TIFF format. Can it be done? Please help by providing some references.

6 Answers

Intro Note:

  1. This answer cover the Bounty Question; which is: How do we convert multiple files into 1 tiff? For example, let's say have pdfs, jpegs, pngs, and I'd like to create 1 tiff out of them?
  2. In this answer I use .net implementation of https://imagemagick.org/index.php for image manipulation and and Ghostscript for helping read an AI/EPS/PDF/PS file so we can translate it to image files both are credible and official source.
  3. After I answered this question I got some extra question in my email asking other merging options, I have therefore extended my answer.

IMO there are 2 steps to your goal:

  1. Install required tools for pdf conversion
  2. Take all images including pdf formatted files from source and merge them together in one tiff file.

1. Install tools that helps Pdf to Image conversion:

Step 1 is only required if you intend to convert AI/EPS/PDF/PS file formats. Otherwise just jump to step2.

To make it possible converting pdf to any image format, we need a library that can read pdf files and we need a tool to convert it to image type. For this purpose, we will need to install Ghostscript (GNU Affero General Public License).

Here after, we need to install ImageMagick.net for .net in Visual Studio, nuget link.

So far so good.

2. Code part

Second and Last step is we need to read files (png, jpg, bmp, pdf etc) from folder location and add each file to MagickImageCollection, then we have several options to merge use AppendHorizontally, AppendVertically, Montage or Multiple page Tiff. ImageMagick has tons of features, like resizing, resolution etc, this is just example to demonstrate merging features:

public static void MergeImage(string src, string dest, MergeType type = MergeType.MultiplePage)
{
    var files = new DirectoryInfo(src).GetFiles();

    using (var images = new MagickImageCollection())
    {
        foreach (var file in files)
        {
            var image = new MagickImage(file)
            {
                Format = MagickFormat.Tif,
                Depth = 8,
            };
            images.Add(image);
        }

        switch (type)
        {
            case MergeType.Vertical:
                using (var result = images.AppendVertically())
                {
                    result.AdaptiveResize(new MagickGeometry(){Height = 600, Width = 800});
                    result.Write(dest);
                }
                break;
            case MergeType.Horizontal:
                using (var result = images.AppendHorizontally())
                {
                    result.AdaptiveResize(new MagickGeometry(){Height = 600, Width = 800});
                    result.Write(dest);
                }
                break;
            case MergeType.Montage:
                var settings = new MontageSettings
                {
                    BackgroundColor = new MagickColor("#FFF"),
                    Geometry = new MagickGeometry("1x1<")
                };

                using (var result = images.Montage(settings))
                {
                    result.Write(dest);
                }
                break;
            case MergeType.MultiplePage:
                images.Write(dest);
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, "Un-support choice");
        }

        images.Dispose();
    }
}

public enum MergeType
{
    MultiplePage,
    Vertical,
    Horizontal,
    Montage
}

To run the code

public static void Main(string[] args)
{
    var src = @"C:\temp\Images";
    var dest1 = @"C:\temp\Output\MultiplePage.tiff";
    var dest2 = @"C:\temp\Output\Vertical.tiff";
    var dest3 = @"C:\temp\Output\Horizontal.tiff";
    var dest4 = @"C:\temp\Output\Montage.tiff";

    MergeImage(src, dest1);
    MergeImage(src, dest2, MergeType.Vertical);
    MergeImage(src, dest3, MergeType.Horizontal);
    MergeImage(src, dest4, MergeType.Montage);
}

Here is 4 input files in C:\temp\Images:

enter image description here enter image description here enter image description here enter image description here

After running the code, we get 4 new files under C:\temp\Output looks like this:

enter image description here 4 page Multiple Page Tiff

enter image description here 4 image Vertical Merge

enter image description here 4 image Horizontal Merge

enter image description here 4 image Montage Merge

Final note:

  1. it is possible to merge multiple images to tiff using System.Drawing; and using System.Drawing.Imaging; with out using ImageMagick, but pdf does require a third party conversion library or tool, therefore I use Ghostscript and ImageMagick for C#.
  2. ImageMagick has many features, so you can change the resolution, size of output file etc. it is well recognized library.

Disclaimer: A part of this answer is taken from my my personal web site https://itbackyard.com/how-to-convert-ai-eps-pdf-ps-to-image-file/ with source code to github.

To be covert the image in tif format.In the below example to be convert the image and set to a text box.to be see the image in text box is (.tif formate).This sources code is working.

private void btn_Convert(object sender, EventArgs e)
    {
        string newName = System.IO.Path.GetFileNameWithoutExtension(CurrentFile);
        newName = newName + ".tif";
        try
        {
            img.Save(newName, ImageFormat.Tiff);
        }
        catch (Exception ex)
        {
            string error = ee.Message.ToString();
            MessageBox.Show(MessageBoxIcon.Error);

        }
        textBox2.Text = System.IO.Path.GetFullPath(newName.ToString());
    }

ImageMagick command line can do that easily. It is supplied on most Linux systems and is available for Mac or Windows also. See https://imagemagick.org/script/download.php

convert image.suffix -compress XXX image.tiff


or you can process a whole folder of files using

mogrify -format tiff -path path/to/output_directory *


ImageMagick supports combining multiple images into a multi-page TIFF. And the images can be of mixed types even including PDF.

convert image1.suffix1 image2.suffix2 ... -compress XXX imageN.suffixN output.tiff


You can choose from a number of compression formats or no compression.

See

https://imagemagick.org/script/command-line-processing.php

https://imagemagick.org/Usage/basics/

https://imagemagick.org/Usage/basics/#mogrify

https://imagemagick.org/script/command-line-options.php#compress


Or you can use Magick.Net for a C# interface. See https://github.com/dlemstra/Magick.NET

Main ImageMagick page is at https://imagemagick.org.

Supported formats are listed at https://imagemagick.org/script/formats.php

You can easily process your images to resize them, convert to grayscale, filter (sharpen), threshold, etc, all in the same command line.

See

https://imagemagick.org/Usage/

https://imagemagick.org/Usage/reference.html

This is how I convert images that are uploaded to a website. Changed it so it outputs Tiff files. The method input and outputs a byte array so it can easily be used in a variety of ways. But you can easily modify it.

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public byte[] ConvertImageToTiff(byte[] SourceImage)
{
    //create a new byte array
    byte[] bin = new byte[0];

    //check if there is data
    if (SourceImage == null || SourceImage.Length == 0)
    {
        return bin;
    }

    //convert the byte array to a bitmap
    Bitmap NewImage;
    using (MemoryStream ms = new MemoryStream(SourceImage))
    {
        NewImage = new Bitmap(ms);
    }

    //set some properties
    Bitmap TempImage = new Bitmap(NewImage.Width, NewImage.Height);
    using (Graphics g = Graphics.FromImage(TempImage))
    {
        g.CompositingMode = CompositingMode.SourceCopy;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;
        g.DrawImage(NewImage, 0, 0, NewImage.Width, NewImage.Height);
    }
    NewImage = TempImage;

    //save the image to a stream
    using (MemoryStream ms = new MemoryStream())
    {
        EncoderParameters encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L);

        NewImage.Save(ms, GetEncoderInfo("image/tiff"), encoderParameters);
        bin = ms.ToArray();
    }

    //cleanup
    NewImage.Dispose();
    TempImage.Dispose();

    //return data
    return bin;
}


//get the correct encoder info
public ImageCodecInfo GetEncoderInfo(string MimeType)
{
    ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
    for (int j = 0; j < encoders.Length; ++j)
    {
        if (encoders[j].MimeType.ToLower() == MimeType.ToLower())
            return encoders[j];
    }
    return null;
}

To test

var oldImage = File.ReadAllBytes(Server.MapPath("OldImage.jpg"));
var newImage = ConvertImageToTiff(oldImage);
File.WriteAllBytes(Server.MapPath("NewImage.tiff"), newImage);
Related