Take the 2-minute tour ×

I'm using libtiff to write a image class that load and write tiff images. However, it is quite difficult to use them I keep getting an error, my code is:

  TIFF *out = TIFFOpen(filename.c_str(),"w") ;
    if (out)
        uint32 imagelength, imagewidth;
        uint8 * buf;
        uint32 row, col, n;
        uint16 config, nsamples;
        imagewidth = dims[0] ;
        imagelength = dims[1] ;
        config = PLANARCONFIG_CONTIG ;
        nsamples = cn ;

        TIFFSetField(out, TIFFTAG_IMAGELENGTH, &imagelength);
        TIFFSetField(out, TIFFTAG_IMAGEWIDTH, &imagewidth);
        TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, &nsamples);
        TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8) ;
        TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(out, imagewidth*nsamples));

        std::cout <<nsamples << std::endl ;

        buf = new uint8 [imagewidth*nsamples] ;

        for (row = 0; row < imagelength; row++){

               for(col=0; col < imagewidth; col++){

                   for(n = 0 ; n < nsamples ; ++n)
                       Vec<T,cn>* temp = image_data[imagewidth*row+col] ;
                       buf[col*nsamples+n] = static_cast<uint8> ((*temp)[n]) ;
               if (TIFFWriteScanline(out, buf, row) != 1 ) 
                   std::cout << "Unable to write a row." <<std::endl ;
                   break ;

    } ...

and the error message is:

test_write.tiff: Integer overflow in TIFFScanlineSize.
test_write.tiff: Integer overflow in TIFFScanlineSize.

my call code is like this:

Image<unsigned char,3> testimg ; //uint8 is unsigned char
testimg.read_image("test.tiff") ;
testimg.write_image("test_write.tiff") ;

I can get the test_write.tiff written, but I cannot open it with any of image browser, and the file size is not the same as before.


share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

I think I just solved my own problem, since I cannot find a similar issue on stackoverflow, maybe this will help others.

The reason is TIFFSetField takes in value rather than reference of the original varible.

So everything works fine after change as follows:

TIFFSetField(out, TIFFTAG_IMAGELENGTH, imagelength);
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, imagewidth);

I got the tip from using imagej to open the written file, it shows that the file has wrong sample per pixel.

share|improve this answer
I had the same problem recently. –  nobar Feb 25 '13 at 9:39
add comment

Your Answer


