Converting 32bit tiff to 16bit tiff libtiff

Hey guys,

I've trying to convert a 32 bit tiff to 16 bit using libtiff. I'm hardly a master with this stuff and everything I'm trying isn't working. I wonder if anyone here could possibly shed some light on what I'm doing wrong?

With the code below, the file is written out, but it's stretched(only showing half) and looks corrupted.
However, if I set the bitspersample to 32 on the out image it writes fine. I'm guessing this is normal and I'm missing something else needed to convert the 32bit data to 16bit.

This is what i'm trying:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    TIFF *image;
    TIFF *out;

    uint32 width, height;
    int imagesize;
    uint16 BitsPerSample; 
    uint16 SamplesPerPixel;
    uint16 i;

    uint32 rowsPerStrip, stripBytesCounts;


    tdata_t buf;
    uint32 row;


    image = TIFFOpen("test.tif","r");
    out = TIFFOpen("new.tif", "w");

    TIFFGetField(image, TIFFTAG_IMAGEWIDTH, &width);
    TIFFGetField(image, TIFFTAG_IMAGELENGTH, &height);
    TIFFGetField(image, TIFFTAG_BITSPERSAMPLE, &BitsPerSample);
    TIFFGetField(image, TIFFTAG_SAMPLESPERPIXEL, &SamplesPerPixel);
    TIFFGetField(image, TIFFTAG_ROWSPERSTRIP, &rowsPerStrip);
    TIFFGetField(image, TIFFTAG_STRIPBYTECOUNTS, &stripBytesCounts);

    //Setup output
    TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width);
    TIFFSetField(out, TIFFTAG_IMAGELENGTH, height);
    TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, SamplesPerPixel);
    TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 16);
    TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsPerStrip);
    TIFFSetField(out, TIFFTAG_XRESOLUTION, 72.0);
    TIFFSetField(out, TIFFTAG_YRESOLUTION, 72.0);
    TIFFSetField(out, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH);
    TIFFSetField(out, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
    TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
    TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_NONE);


    tsize_t scanlinesize = TIFFScanlineSize(image);

    buf = _TIFFmalloc(scanlinesize);

    if (!buf)
	    if (buf == NULL){
		    fprintf (stderr,"Could not allocate memory!\n");
		    exit(0);
    }

    for (row = 0; row < height; row++)
    {
		if (TIFFReadScanline(image, buf, row, 0) < 0) {
			TIFFError(TIFFFileName(image),
				  "Error, can't read scanline %lu",
				  (unsigned long) row);
			break;
		}
		if (TIFFWriteScanline(out, buf, row, 0) < 0) {
			TIFFError(TIFFFileName(out),
				  "Error, can't write scanline %lu",
				  (unsigned long) row);
			break;
		}
    }
    _TIFFfree(buf); 

    TIFFClose(image);
    TIFFClose(out);


Would really appreciate any help you can give. Cheers guys.
Last edited on
Topic archived. No new replies allowed.