Search code examples
c++tifflibtiff

How to write tiles on multi pages using LibTIFF


I am trying to write tiles on a multi-page tiff (pyramidal tiff) using LibTIFF:

for(int pageNum=0; pageNum<pageCount; pageNum++)
{
    // processing for getting tiles (decode and resize for each page)
    ////

    TIFFSetField(tiff_out, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE);
    TIFFSetField(tiff_out, TIFFTAG_PAGENUMBER, pageNum);
    //TIFFSetField(tiff_out, TIFFTAG_IMAGEWIDTH, imageWidth); // <- cannot be done with en error message(cannot change the value while processing)
    //TIFFSetField(tiff_out, TIFFTAG_IMAGELENGTH, imageHeight); // <- cannot be done with en error message(cannot change the value while processing)
    TIFFWriteEncodedTile(tiff_out, tileNumberOnPage, buff, -1);   
}

When I tried to write only single page, I worked fine. But when trying to do with multi-pages, the result shows overlapped images. It seemed that all pages are shown on the first page.

I checked the resulting TIFF file with the tiffinfo command. It shows that the page number is the last page number, but it only shows the information of the first page (i.e. it shows only one page).

Is there other setting for writing tiles on multi-page, pyramidal TIFF?

(I also tried setting FILETYPE_PAGE as TIFFTAG_SUBFILETYPE.)


Solution

  • To create mutliple pages (directories) in the TIFF file, use the TIFFWriteDirectory function. It will write the tags and data as specified up to that point to the current directory, and start a new one. TIFFClose writes the tags and data to the current directory and closes the file.

    Thus, to create a file with two directories, you first create a new file, set tags and write tiles, call TIFFWriteDirectory, set tags and write tiles, and call TIFFClose.

    For example, you could modify your code to be:

    for(int pageNum=0; pageNum<pageCount; pageNum++)
    {
        // processing for getting tiles (decode and resize for each page)
        if(pageNum>0) {
            TIFFWriteDirectory(tiff_out);
        }
        TIFFSetField(tiff_out, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE);
        TIFFSetField(tiff_out, TIFFTAG_IMAGEWIDTH, imageWidth);
        TIFFSetField(tiff_out, TIFFTAG_IMAGELENGTH, imageHeight);
        TIFFWriteEncodedTile(tiff_out, tileNumberOnPage, buff, -1);   
    }
    TIFFClose(tiff_out);