Convert various image formats (jpg, gif, png, etc.) to TIFF format

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

So, I need to convert other formats to TIFF format. It can be done? Please help by providing some links.

+18
source share
6 answers

If you create an Image object in .NET, you can save it as a TIFF. This is one of many ImageFormat at your disposal.

Example:

 var png = Image.FromFile("some.png"); png.Save("a.tiff", ImageFormat.Tiff); 

You need to include the System.Drawing assembly project in the project. This build will give you many image manipulation capabilities. Hope this helps.

+22
source

Intro Note:

  1. This answer covers the issue of rewards; what: how do we convert multiple files to 1 tiff? For example, let's say there is PDF, JPEG, PNG, and I would like to create 1 TIFF of them?
  2. In this answer, I use the .net implementation of https://imagemagick.org/index.php for working with images and Ghostscript to help read the AI ​​/ EPS / PDF / PS file so that we can translate it into image files that are valid and official sources.
  3. After I answered this question, in my email I received an additional question with other merge options, so I expanded my answer.

IMO there are 2 steps to your goal:

  1. Install the necessary tools to convert to PDF
  2. Take all images, including PDF files, from the source and combine them into a single TIFF file.

1. Install tools to help convert Pdf to image:

Step 1 is only required if you are going to convert AI / EPS / PDF / PS file formats. Otherwise, just go to step 2.

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

After that, we need to install ImageMagick.net for .net in Visual Studio, the nua link .

So far so good.

2. Code part

The second and final step - we need to read the files (png, jpg, bmp, pdf, etc.) from the folder and add each file to the MagickImageCollection , then we have several options for merging, use AppendHorizontally , AppendVertically , Montage or multi-page tiff. ImageMagick has many functions, such as resizing, resolution, etc., This is just an example that demonstrates the combination of functions:

 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 are 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 in the folder C: \ temp \ Output, which look like this:

enter image description here 4-page multi-page Tiff

enter image description here Vertical merge 4 images

enter image description here Horizontal merge of 4 images

enter image description here 4 images of Montage Merge

Final note:

  1. You can combine multiple images using System.Drawing; and using System.Drawing.Imaging; without using ImageMagick, but pdf requires a third-party conversion library or tool, so I use Ghostscript and ImageMagick for C #.
  2. ImageMagick has many functions, so you can change the resolution, output file size, etc. This is a well-recognized library.

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

+13
source

To be hidden image in TIF format. In the example below, to convert the image and set to a text box. To see the image in the text box is (.tif format). This source code works.

 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()); } 
+4
source

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

 convert image.suffix -compress XXX image.tiff 


or you can process the whole file folder using

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


ImageMagick supports combining multiple images into multi-page TIFF. And images can be of mixed type, including PDF.

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


You can choose one of several compression formats or without 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 the C # interface. See https://github.com/dlemstra/Magick.NET

The ImageMagick homepage is located at https://imagemagick.org .

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

You can easily process images to resize them, convert them to shades of gray, filter (sharpness), threshold values, etc., all on one command line.

See

https://imagemagick.org/Usage/

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

+3
source

I tested this with jpg, bmp, png and gif. Works for one-time and multi-page tiff creation. Give it the full path to the file. Hope this helps someone. (extracted from MSDN)

 public static string[] ConvertJpegToTiff(string[] fileNames, bool isMultipage) { EncoderParameters encoderParams = new EncoderParameters(1); ImageCodecInfo tiffCodecInfo = ImageCodecInfo.GetImageEncoders() .First(ie => ie.MimeType == "image/tiff"); string[] tiffPaths = null; if (isMultipage) { tiffPaths = new string[1]; System.Drawing.Image tiffImg = null; try { for (int i = 0; i < fileNames.Length; i++) { if (i == 0) { tiffPaths[i] = String.Format("{0}\\{1}.tif", Path.GetDirectoryName(fileNames[i]), Path.GetFileNameWithoutExtension(fileNames[i])); // Initialize the first frame of multipage tiff. tiffImg = System.Drawing.Image.FromFile(fileNames[i]); encoderParams.Param[0] = new EncoderParameter( System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.MultiFrame); tiffImg.Save(tiffPaths[i], tiffCodecInfo, encoderParams); } else { // Add additional frames. encoderParams.Param[0] = new EncoderParameter( System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); using (System.Drawing.Image frame = System.Drawing.Image.FromFile(fileNames[i])) { tiffImg.SaveAdd(frame, encoderParams); } } if (i == fileNames.Length - 1) { // When it is the last frame, flush the resources and closing. encoderParams.Param[0] = new EncoderParameter( System.Drawing.Imaging.Encoder.SaveFlag, (long)EncoderValue.Flush); tiffImg.SaveAdd(encoderParams); } } } finally { if (tiffImg != null) { tiffImg.Dispose(); tiffImg = null; } } } else { tiffPaths = new string[fileNames.Length]; for (int i = 0; i < fileNames.Length; i++) { tiffPaths[i] = String.Format("{0}\\{1}.tif", Path.GetDirectoryName(fileNames[i]), Path.GetFileNameWithoutExtension(fileNames[i])); // Save as individual tiff files. using (System.Drawing.Image tiffImg = System.Drawing.Image.FromFile(fileNames[i])) { tiffImg.Save(tiffPaths[i], ImageFormat.Tiff); } } } return tiffPaths; } 
+2
source

So I convert the images uploaded to the site. Changed so that it outputs Tiff files. The method inputs and outputs a byte array, so it can be easily used in various ways. But you can easily change 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; } 

For check

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

All Articles