I know thumbnail.c includes some code that creates a thumbnail and places it in a sub IDF, but there is a lot going on in that code (generating the thumbnail, applying a contrast curve, etc.) and I am having difficulty reproducing just writing a thumbnail. Google has not been any help either.
My question is, after I have opened an output file and have a TIFF*, I have my thumbnail data all ready to go (as well as my main image data), how do I add them in such a way that the thumbnail is in a sub IFD of the main image IFD?
So after digging around through the libtiff source code for a while, I stumbled across this in tif_dirwrite.c:
(I included the copyright info because I wasn't sure if I had to when posting code from the library here)
So, to answer my own question (how to write a thumbnail in a sub-IFD of the main image IFD):
I hope that this helps somebody and that they don't have to expend as much effort as I did to figure out how to do this. It really is a shame that libtiff is so poorly documented, especially considering how widely it is used.
I think @KSletmoe has pointed out a key point that the SubIFD tag(330) should be added in IFD0 before you write any subIFD, but there is still a problem.
The definition of SubIFD tag is "Offset to child IFDs". So, if you don't set the offset correctly, tiff parser can not parse the whole tiff correctly.
There are two ways to handle this situation.
First, pre-calculate the size of each IFD/SubIFD, then fill-in to SubIFD tag when you set, instead of setting 0x0.
Or you can write every IFD as normal then go back to IFD0 and add SubIFD tag with final offset that calculated by libtiff. Like following:
You may need to add flowing function in tif_dir.c
Thanks for @KSletmoe. Hope this can help someone, and looking forward some much elegant way to do so.