2012-02-08 47 views
3

我有一个Windows服务,它尝试使用System.Drawing命名空间中的Image类获取TIFF文件中的页数。如何使用Windows服务中的代码获取tiff文件中的页数

using System.Drawing; 

    private int GetNumberOfPagesFromTiffFile(string filePath) 
    { 
     int pageCount = 0; 
     Image Tiff = Image.FromFile(filePath); 
     pageCount = Tiff.GetFrameCount(FrameDimension.Page); 
     Tiff.Dispose(); 

     return pageCount; 
    } 

但微软的文档http://msdn.microsoft.com/en-us/library/system.drawing.aspx说不要在Windows服务中使用System.Drawing中。他们建议使用Windows Imaging Component。我下载了它,看看它是否有办法获取TIFF文件中的页数,但是我安装时遇到错误。所以我还没有我的答案。

我很好奇别人用什么来获取Windows服务中TIFF文件的页数。

+3

如何只走IFD链的页数?这非常简单,并且不需要任何超过CreateFile(),ReadFile() – BitBank 2012-02-09 04:09:31

+0

感谢BitBank,这个想法工作得很好,它也更快! 但是,我原本不知道你是什么意思的“IFD链”,因为我根本不知道任何有关TIFF文件。在阅读了关于TIFF文件格式的一些网页后,我终于找到了你正在谈论的内容。 – 2012-02-10 16:41:48

+0

对不起,我的回答如此简洁。下次有人问,我会提供一个代码示例。 – BitBank 2012-02-13 23:50:08

回答

1

这里是一个通用的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() 
相关问题