这里是一个通用的C函数来计算的TIFF文件
uint16_t TIFFSHORT(unsigned char *buffer, bool bMotorola)
{
uint16_t s;
if (bMotorola)
s = (buffer[0] << 8) + buffer[1];
else
s = buffer[0] + (buffer[1] << 8);
return s;
}
uint32_t TIFFLONG(unsigned char *buffer, bool bMotorola)
{
uint32_t l;
if (bMotorola)
l = (buffer[0] << 24) + (buffer[1] << 16) + (buffer[2] << 8) + buffer[3];
else
l = buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
return l;
}
int TIFFPageCount(char *filename)
{
int i, iTags, IFD;
int iOffset, iTotalPages;
unsigned char buf[8];
FILE *handle;
bool bMotorola;
int iFileSize;
handle = fopen((char *)filename, "rb");
if (handle == NULL)
return 0;
// get the file size
fseek(handle, 0, SEEK_END);
iFileSize = (int)ftell(handle);
fseek(handle, 0, SEEK_SET);
i = fread(buf, 1, 8, handle); // Read TIFF header and first IFD offset
if (buf[0] != 'I' && buf[0] != 'M')
{
fclose(handle);
return 0; // Not a TIFF file
}
bMotorola = (buf[0] == 'M'); // get the byte order
IFD = TIFFLONG(&buf[4], bMotorola); // Read the first IFD pointer
if (IFD < 8 || IFD > iFileSize) // corrupt file, don't process it
{
fclose(handle);
return 0;
}
iTotalPages = 0;
while(IFD != 0 && IFD < iFileSize-4) // count the number of pages
{
fseek(handle, IFD, SEEK_SET);
fread(buf, 1, 2, handle); // get the number of tags in this page
iTags = TIFFSHORT(buf, bMotorola); // Number of tags in this dir
i = iTags * 12 + 2; // Offset to next IFD in chain
if (iTags > 256) // Invalid header, abort
break;
fseek(handle, IFD+i, SEEK_SET);
fread(buf, 1, 4, handle); // read the next IFD value; 0 means end of chain
IFD = TIFFLONG(buf, bMotorola);
iTotalPages++;
}
fclose(handle);
return iTotalPages;
} // TIFFPageCount()
如何只走IFD链的页数?这非常简单,并且不需要任何超过CreateFile(),ReadFile() – BitBank 2012-02-09 04:09:31
感谢BitBank,这个想法工作得很好,它也更快! 但是,我原本不知道你是什么意思的“IFD链”,因为我根本不知道任何有关TIFF文件。在阅读了关于TIFF文件格式的一些网页后,我终于找到了你正在谈论的内容。 – 2012-02-10 16:41:48
对不起,我的回答如此简洁。下次有人问,我会提供一个代码示例。 – BitBank 2012-02-13 23:50:08