c++ - 在 C++ 中使用 libtiff 写入图像时出现问题,在 TIFFScanlineSize 中出现整数溢出

标签 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);
    } ...

错误信息是:

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

我的调用代码是这样的:

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

我可以写出test_write.tiff,但是用任何图片浏览器都打不开,而且文件大小和以前不一样。

谢谢

最佳答案

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

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

因此更改后一切正常,如下所示:

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

我从使用 imagej 打开写入的文件得到了提示,它表明该文件的每个像素样本错误。

关于c++ - 在 C++ 中使用 libtiff 写入图像时出现问题,在 TIFFScanlineSize 中出现整数溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13391498/

相关文章:

c++ - 将 LibTiff 安装到 Visual Studio 2010

powershell - 如何在 Powershell 中复制 Azure 资源管理器模板 uniquestring() 函数?

c++ - 除复制省略外,还有没有其他机制可以优化C++中的过度构造?

c++ - 为什么删除移动构造函数时我的对象没有被复制?

c++ - 函数声明/函数定义

javascript - 达到 10 次摘要迭代,正在中止(作用域函数问题)

c++ - 模板的复制构造函数

linux - 如何在没有root权限的情况下在ubuntu 16.04上手动下载编译安装tiff5库?

c++ - 无法在 Mac 上使用 Libtiff 写入 TIFF 文件

c++ - C++ 中的比较器函数的含义和工作原理?