Question

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_PLANARCONFIG, PLANARCONFIG_CONTIG);
        TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, &nsamples);
        TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_LZW) ;
        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 ;
               }  
        }

        _TIFFfree(buf);
        TIFFClose(out);
    } ...

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.

Thanks

Was it helpful?

Solution

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);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nsamples);

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top