Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a tiff file's dimension and resolution without loading it first

Tags:

c#

memory

tiff

How to read a tiff file's dimension (width and height) and resolution (horizontal and vertical) without first loading it into memory by using code like the following. It is too slow for big files and I don't need to manipulate them.

Image tif = Image.FromFile(@"C:\large_size.tif");
float width = tif.PhysicalDimension.Width;
float height = tif.PhysicalDimension.Height;
float hresolution = tif.HorizontalResolution;
float vresolution = tif.VerticalResolution;
tif.Dispose();

Edit:

Those tiff files are Bilevel and have a dimension of 30x42 inch. The file sizes are about 1~2 MB. So the method above works Ok but slow.

like image 457
z1x2 Avatar asked Oct 29 '10 00:10

z1x2


2 Answers

Ran into this myself and found the solution (possibly here). Image.FromStream with validateImageData = false allows you access to the information you're looking for, without loading the whole file.

using(FileStream stream = new FileStream(@"C:\large_size.tif", FileMode.Open, FileAccess.Read))
{
  using(Image tif = Image.FromStream(stream, false, false))
  {
    float width = tif.PhysicalDimension.Width;
    float height = tif.PhysicalDimension.Height;
    float hresolution = tif.HorizontalResolution;
    float vresolution = tif.VerticalResolution;
  }
}
like image 97
Joel Rondeau Avatar answered Oct 21 '22 20:10

Joel Rondeau


As far as I know, all classes from System.Drawing namespace load image data immediately when image is open.

I think LibTiff.Net can help you to read image properties without loading image data. It's free and open-source (BSD license, suitable for commercial applications).

Here is a sample for your task (error checks are omitted for brevity):

using BitMiracle.LibTiff.Classic;

namespace ReadTiffDimensions
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Tiff image = Tiff.Open(args[0], "r"))
            {
                FieldValue[] value = image.GetField(TiffTag.IMAGEWIDTH);
                int width = value[0].ToInt();

                value = image.GetField(TiffTag.IMAGELENGTH);
                int height = value[0].ToInt();

                value = image.GetField(TiffTag.XRESOLUTION);
                float dpiX = value[0].ToFloat();

                value = image.GetField(TiffTag.YRESOLUTION);
                float dpiY = value[0].ToFloat();
            }
        }
    }
}

Disclaimer: I am one of the maintainers of the library.

like image 39
Bobrovsky Avatar answered Oct 21 '22 21:10

Bobrovsky