尝试将“ExtraSamples”标签应用到要写入的 TIFF 文件时出现错误

MBr*_*ley 3 c++ file-io tiff libtiff

我有一个程序可以获取图像并将其写入 TIFF 文件。图像可以是灰度(8 位)、带 Alpha 通道的灰度(16 位)、RGB(24 位)或 ARGB(32 位)。写出没有 Alpha 通道的图像时没有任何问题,但对于带有 Alpha 的图像,当我尝试设置额外的样本标记时,我会被发送到 TIFFSetErrorHandler 设置的 TIFF 错误处理例程。传入的消息<filename>: Bad value 1 for "ExtraSamples"位于 _TIFFVSetField 模块中。下面是一些示例代码:

#include "tiff.h"
#include "tiffio.h"
#include "xtiffio.h"
//Other includes

class MyTIFFWriter
{
public:
    MyTIFFWriter(void);

    ~MyTIFFWriter(void);

    bool writeFile(MyImage* outputImage);
    bool openFile(std::string filename);
    void closeFile();

private:
    TIFF* m_tif;
};

//...

bool MyTIFFWriter::writeFile(MyImage* outputImage)
{
    // check that we have data and that the tiff is ready for writing
    if (outputImage->getHeight() == 0 || outputImage->getWidth() == 0 || !m_tif)
        return false;

    TIFFSetField(m_tif, TIFFTAG_IMAGEWIDTH, outputImage->getWidth());
    TIFFSetField(m_tif, TIFFTAG_IMAGELENGTH, outputImage->getHeight());
    TIFFSetField(m_tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
    TIFFSetField(m_tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);

    if (outputImage->getColourMode() == MyImage::ARGB)
    {
        TIFFSetField(m_tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
        TIFFSetField(m_tif, TIFFTAG_BITSPERSAMPLE, outputImage->getBitDepth() / 4);
        TIFFSetField(m_tif, TIFFTAG_SAMPLESPERPIXEL, 4);
        TIFFSetField(m_tif, TIFFTAG_EXTRASAMPLES, EXTRASAMPLE_ASSOCALPHA);  //problem exists here
    } else if (/*other mode*/)
        //apply other mode settings

    //...

    return (TIFFWriteEncodedStrip(m_tif, 0, outputImage->getImgDataAsCharPtr(), 
        outputImage->getWidth() * outputImage->getHeight() *
        (outputImage->getBitDepth() / 8)) != -1);
}
Run Code Online (Sandbox Code Playgroud)

据我所知,标签永远不会写入文件。幸运的是,GIMP 仍然可以识别附加通道是 Alpha,但其他一些需要读取这些 TIFF 的程序就没有那么慷慨了。我是否缺少必须在 TIFFTAG_EXTRASAMPLES 之前设置的标签?我是否缺少其他需要存在的标签?任何帮助,将不胜感激。

小智 5

我找到了解决方案。Extra_Samples 字段不是 uint16,而是首先是一个计数(即 uint16),然后是该大小的数组(类型为 uint16)。因此,该调用应如下所示:

uint16 out[1];
out[0] = EXTRASAMPLE_ASSOCALPHA;

TIFFSetField( outImage, TIFFTAG_EXTRASAMPLES, 1, &out );
Run Code Online (Sandbox Code Playgroud)

其原因是允许超过一个额外样本。

希望这可以帮助!

干杯,卡斯帕