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:
1 2 3 4 5 6 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #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[(w*h)-((c_h*w)+(w-c_w))]%256 << " " ; } cout << endl; } } _TIFFfree(raster); } TIFFClose(tif); } } [/sourcecode] 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:
1 | . /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
[…] built all this on a mac. If you want to do the same, you’ll need to install libtiff and […]
[…] this advice on stackoverflow. I on purpose used the same version as Apple and built it like in this simple example. I have not found help for Xcode or iOS on the Libtiff homepage, […]