Simple libtiff Example

First, you have to install libtiff. On Linux it’s almost certainly in your repository you should install a package with an name similar to libtiff-dev.

On MacOS X I did the following:

curl ftp://ftp.remotesensing.org/pub/libtiff/tiff-3.9.5.zip > tiff-3.9.5.zip
tar xvzf tiff-3.9.5.zip
cd tiff-3.9.5
./configure
make
sudo make install

Then create the following cpp file:

#include "tiffio.h"
#include <iostream>

using namespace std;

main(int argc, char* argv[])
{

  TIFF* tif = TIFFOpen(argv[1], "r");
  if (tif) {
    uint32 w, h;
    size_t npixels;
    uint32* raster;

    TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
    npixels = w * h;

    raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
    if (raster != NULL) {
      if (TIFFReadRGBAImage(tif, w, h, raster, 0)) {


        cout << "P2" << endl;
        cout << w << " " << h << endl;
        cout << 255 << endl;

        for(size_t c_h=0;c_h<h;c_h++) {
          for(size_t c_w=0;c_w<w;c_w++) {
            cout << raster&#91;(w*h)-((c_h*w)+(w-c_w))&#93;%256 << " ";
          }
          cout << endl;
        }

      }
      _TIFFfree(raster);
    }
    TIFFClose(tif);
  }
}
&#91;/sourcecode&#93;

This program converts a tiff file to a PGM (portable grey map) file. PGM is a simple text based format, this makes it very easy to debug. You can read more about PGM on <a href="http://en.wikipedia.org/wiki/Portable_graymap">wikipedia</a>.

Note: It's not converting the RGB value to grey very well it's simply modding the value for the example.

Compile the program as follow (on MacOS you'll need to have install XCode or another gcc version):

[sourcecode language="bash"]
g++ tiffsimple.cpp -ltiff

Then run it as:

./a.out inputfile.tif

You can view the resulting PGM file with ImageMagick.

Notes

You can also transform the TIFF coordinates rather than performing the transformation yourself when converting to PGM as follows:

#include “tiffio.h”
#include

using namespace std;

main(int argc, char* argv[])
{

TIFF* tif = TIFFOpen(argv[1], “r”);
if (tif) {
uint32 w, h;
size_t npixels;
uint32* raster;

TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
npixels = w * h;

raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
if (raster != NULL) {
if (TIFFReadRGBAImageOriented(tif, w, h, raster,ORIENTATION_TOPLEFT, 0)) {

cout << "P2" << endl; cout << w << " " << h << endl; cout << 255 << endl; for(size_t c_h=0;c_h