2009.05.19 12:32 "[Tiff] Heap corruption caused by TIFFRGBAImageGet() + TIFFSetDirectory() + TIFFRewriteDirectory()", by

2009.06.14 23:11 "Re: [Tiff] Tiff 16 bit and 32 bit images", by Keshab Neupane

Hi All,

Can you please look at my code and check what am I doing wrong.

I have to copy data from tiff 16 bit image into buffer and then into destination buffer.

/* tiffinfo gives
TIFF Directory at offset 0x8 (8)
  Image Width: 2160 Image Length: 900
  Bits/Sample: 16
  Sample Format: unsigned integer
  Compression Scheme: None
  Photometric Interpretation: min-is-black
  Samples/Pixel: 1
  Rows/Strip: 1
*/

#include <stdio.h>
#include "tiffio.h"
#include <stdlib.h>

int main(int argc, char **argv){

    TIFF *tif;

    uint16 bps, spp, bpp, photo, sampleFormat;

    uint32 width, height;

    char *buffer;
    char *filename = argv[1];
    tif = TIFFOpen(filename, "r");
    if (!tif)
    {
        fprintf (stderr, "Can't open %s for reading\n", filename);
        return 2;
    }

TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);

TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);

    TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bps);
    TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
    bpp = bps * spp;
    TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photo);
    TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &sampleFormat);

    int linesize = TIFFScanlineSize(tif);
    buffer = (char*)malloc(linesize * height);

    for (unsigned int i = 0; i < height; i++)
        TIFFReadScanline(tif, &buffer[i * linesize], i, 0);
       
    printf("sample format is %u\n",sampleFormat);
    printf("photometric interpretation is %u\n",photo);

    char *destination;
    if(sampleFormat == 1){ // Check for unsigned integer case
        // This is where I am doing wrong
        for(unsigned int i =0; i < height/2; i++){

            *((uint16*)destination)= ((uint16*)buffer)[i]; // copy data from buffer to destination

            // reason why I am casting with uint16 is because sample format(image data) are unsigned interger values

            buffer += 2;
            destination += 2;

   }

   TIFFClose(tif);

    free(buffer);

    return 0;
}

My confusion/question,

What am I doing wrong while copying data from buffer to destination?

I know I am doing wrong, but can't figure out how and why?

Here, photometric interpretation is min-is-black, what will happen if I have RGB or greyscale image i.e how do I copy data from buffer to destination?

Sometimes, SAMPLEFORMAT is not given/available, how I can decide what data types are tiff image made from. I need to handle 16 bit signed/unsigned and 32 bit float values!!

Any nice books where I can read all about tiff image format? What are the possible tiff image formats available/theoretically possible?

I googled it but couldn't find any satisfactory result?

Thank you everyone and sorry for asking so many questions,

Keshab