これまで自作の関数でMulti TIFFファイルを書いたり、読んだりしていたのですが、libtiffライブラリを使ってみることにしました。
使うデータは主に8bit、16bitのグレースケールです。
今回は16bitグレースケールsingle TIFFの書き込みです。
Windows、Linuxで解析を行うので、両方でコンパイルできるようにしています。
ソース
環境によっては「nodefaultlib」を付けなくてもコンパイルは通ります。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEXT_MAX 128
// まとめて書き込む
//#define TIFF_WRITE_ALL
#ifdef __GNUC__
#include <tiffio.h>
#endif
#ifdef _WIN32
#include "tiffio.h"
#ifdef _DEBUG
#pragma comment(linker, "/nodefaultlib:\"libcmtd.lib\"")
#else
#pragma comment(linker, "/nodefaultlib:\"libcmt.lib\"")
#endif
#pragma comment(lib, "libtiff.lib")
#endif
int main( int argc, char **argv )
{
int i, j, r;
int width, height;
uint16 *buf;
uint16 *line;
uint16 samplesperpixel, bitspersample;
uint32 tifsize, linesize;
char tiftitle[TEXT_MAX] = { '\0' };
double resolution;
TIFF *tif;
// TIFFパラメータ
width = 512;
height = 256;
resolution = 72.0;
bitspersample = 16;
samplesperpixel = 1;
strcpy(tiftitle, "Test program");
tifsize = width * height * sizeof( uint16 );
buf = ( uint16 * )malloc( tifsize );
if ( buf == NULL )
{
printf("ERROR: Can not get memory [buf] \n");
// exit( EXIT_FAILURE );
return EXIT_FAILURE;
}
// 画像データ
for( i = 0; i < height; i++ )
{
for( j = 0; j < width; j++ )
{
buf[width * i + j] = ( uint16 )(i * j);
}
}
tif = TIFFOpen("write-16bit.tif", "w");
if ( tif == NULL )
{
printf("ERROR: Can not open tiff file \n");
// exit( EXIT_FAILURE );
return EXIT_FAILURE;
}
TIFFSetField(tif, TIFFTAG_SOFTWARE, tiftitle);
TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, bitspersample);
TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel);
TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(tif, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
TIFFSetField(tif, TIFFTAG_XRESOLUTION, resolution);
TIFFSetField(tif, TIFFTAG_YRESOLUTION, resolution);
TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
#ifdef TIFF_WRITE_ALL
// まとめて書き込み
TIFFWriteEncodedStrip(tif, 0, buf, tifsize);
#else
// 1行ずつ書き込む
linesize = width * sizeof( uint16 );
line = ( uint16 * )malloc( linesize );
if ( line == NULL )
{
printf("ERROR: Can not get memory [line] \n");
// exit( EXIT_FAILURE );
return EXIT_FAILURE;
}
for( i = 0 ; i < height; i++ )
{
for ( j = 0; j < width; j++ )
{
line[j] = buf[width * i + j];
}
r = TIFFWriteScanline(tif, line, i, 0);
if ( r == -1 )
{
TIFFClose( tif );
free( buf );
// exit( EXIT_FAILURE );
return EXIT_FAILURE;
}
}
free( line );
#endif
TIFFClose( tif );
free( buf );
return EXIT_SUCCESS;
}
created by Rinker
¥3,960
(2025/11/11 14:58:33時点 楽天市場調べ-詳細)
created by Rinker
¥295
(2025/11/11 14:58:33時点 楽天市場調べ-詳細)


Comments