Using libtiff for luminance/grayscale images

Libtiff is a library for reading and writing TIFF, a small collection of tools for doing simple manipulations of TIFF images on UNIX systems.



#include 
#include 

const int width = 256;
 const int height = 256;
 const int sampleperpixel = 1;
 uint8_t image[height*width];

int main()
 {
 for (int r=0; r < height; r++) {
 for (int c=0; c < width; c++) {
 image[r*width+c] = (r + c) % 256;
 }
 }

TIFF *tif = TIFFOpen("output.tif", "w");
 TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, width);
 TIFFSetField(tif, TIFFTAG_IMAGELENGTH, height);
 TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, sampleperpixel);
 TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 8);
 TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
 TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
 TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
 // TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(tif, width*sampleperpixel));

for (int r=0; r < height; r++) {
 TIFFWriteScanline(tif, &image[r*width], r, 0);
 }

TIFFClose(tif);
 }

For TIFFTAG_PHOTOMETRIC, you need to set it to PHOTOMETRIC_MINISBLACK for the desired results using 1 sample per pixel, 8 bits per sample. This is for grayscale images with only a single channel.

The default from the libtiff examples is PHOTOMETRIC_RGB. This is for conventional images with 3 channels RGB.

Download libtiff here:  http://dl.maptools.org/dl/libtiff/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: