Writing 16 bit single channel image into Tiff

16-bit, c++, file-io, grayscale, libtiff

Solution

Looks like you have two issues in your code.

You are trying to write the whole image with one call to `TIFFWriteEncodedStrip` but at the same time setting `TIFFTAG_ROWSPERSTRIP` to `1` (you should set it to `height()` at such cases).

You are passing wrong value(s) to `TIFFWriteEncodedStrip`. The last parameter is the length of the strip in bytes, and you are clearly passing the length in pixels.

I am not sure if the `&m_data_cropped[0]` parameter points to the first byte of the whole image, so you might want to check correctness of this parameter, too.

Problem

I am trying to save an image in tiff file format. I have used libraw to read the raw data from camera and it gives me unsigned short data. I have done some operation on the data and I want to save the result as a 16 bit grayscale (1 channel) image with Tiff file format. But the result is just a blank image. Even if I use the buffer that keeps the original bayer image it won't save correctly. This is the code that I am using for saving: ``` // Open the TIFF file if((output_image = TIFFOpen("image.tiff", "w")) == NULL){ std::cerr << "Unable to write tif file: " << "image.tiff" << std::endl; } TIFFSetField(output_image, TIFFTAG_IMAGEWIDTH, width()); TIFFSetField(output_image, TIFFTAG_IMAGELENGTH, height()); TIFFSetField(output_image, TIFFTAG_SAMPLESPERPIXEL, 1); TIFFSetField(output_image, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(output_image, TIFFTAG_ROWSPERSTRIP, 1); TIFFSetField(output_image, TIFFTAG_ORIENTATION, (int)ORIENTATION_TOPLEFT); TIFFSetField(output_image, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output_image, TIFFTAG_COMPRESSION, COMPRESSION_NONE); TIFFSetField(output_image, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK); // Write the information to the file tsize_t image_s; if( (image_s = TIFFWriteEncodedStrip(output_image, 0, &m_data_cropped[0], width()*height())) == -1) { std::cerr << "Unable to write tif file: " << "image.tif" << std::endl; } else { std::cout << "Image is saved! size is : " << image_s << std::endl; } TIFFWriteDirectory(output_image); TIFFClose(output_image); ```

Original source