使用C++中的libtiff写入图像的问题,TIFFScanlineSize中的整数溢出

tom*_*234 2 c++ templates libtiff

我正在使用libtiff来编写一个加载和写入tiff图像的图像类.但是,使用它们非常困难我不断收到错误,我的代码是:

  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);
    } ...
Run Code Online (Sandbox Code Playgroud)

并且错误消息是:

test_write.tiff: Integer overflow in TIFFScanlineSize.
test_write.tiff: Integer overflow in TIFFScanlineSize.
Run Code Online (Sandbox Code Playgroud)

我的通话代码是这样的:

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

我可以编写test_write.tiff,但我无法使用任何图像浏览器打开它,文件大小与以前不一样.

谢谢

tom*_*234 6

我想我刚刚解决了自己的问题,因为我在stackoverflow上找不到类似的问题,也许这会对其他人有所帮助.

原因是TIFFSetField接受值而不是原始变量的引用.

所以改变后一切正常如下:

TIFFSetField(out, TIFFTAG_IMAGELENGTH, imagelength);
TIFFSetField(out, TIFFTAG_IMAGEWIDTH, imagewidth);
TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, nsamples);
Run Code Online (Sandbox Code Playgroud)

我得到了使用imagej打开写入文件的提示,它显示该文件每像素有错误的样本.