Search code examples
cheadertagsbinarytiff

How to read TIFF File headers in c?


How can i read a tiff file header in c ?

actually i want to learn TIFF Tag ImageWidth, and TIFF Tag ImageLength.

how can i acces this attributes?

http://www.awaresystems.be/imaging/tiff/tifftags/imagewidth.html http://www.awaresystems.be/imaging/tiff/tifftags/imagelength.html

the c translation of this code can help me :

https://stackoverflow.com/a/9071933/2079158

i don't know c well,
tried something like this :

#include "stdio.h"
#include "stdlib.h"

main()
{
FILE* f = fopen("tifo.tif", "rb");
unsigned char info[500];
fread(info, sizeof(unsigned char), 500, f); 

long int width = *(long int*)&info[256];
short int height = *(short int*)&info[257];

printf("width : %d \n", width);
printf("height : %d \n", height);

fclose(f);
}

what can i do for tiff files??


Solution

  • I solve th problem with this code :

    #include <stdio.h>
    #include "tiffio.h"
    #include <string.h>
    #include <dirent.h>     
    int main(void)
    {
    DIR *dp;
    struct dirent *ep;
    uint32 w, h;
    float xdpi,ydpi;
    
    dp = opendir ("./");
    char file_name[30];
    char last[30];
    if (dp != NULL)
    {
        while (ep = readdir (dp))
        {
            if( ( strstr(ep->d_name, ".tif") != NULL ) || ( strstr(ep->d_name, ".TIF") != NULL ) )
            {
                TIFF* tif = TIFFOpen(ep->d_name, "r");
                TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
                TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
                TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xdpi);
                TIFFGetField(tif, TIFFTAG_YRESOLUTION, &ydpi);
    
                printf("%s --> %d x %d | %.f - %.f \n",ep->d_name, w, h, xdpi,ydpi);
    
                strncpy ( file_name, ep->d_name, ep->d_namlen-4 );
                file_name[ep->d_namlen-4]='\0';
    
                sprintf(last,"%s (%.f x %.f).tif", file_name, (float) ((w/xdpi)*2.54) , (float) ((h/ydpi)*2.54) );
                printf("      |__ %s\n\n",last);
                TIFFClose(tif);
    
                rename(ep->d_name, last);
            }
        }
        (void) closedir (dp);
    }
    else
        perror ("Directory can not open!");
    
    printf("Succesfully finished!");
    getchar();
    
    return 0;
    }