2004.03.24 23:25 "[Tiff] Jpeg compressing a file", by Carl Collin

2004.03.25 15:56 "Re: [Tiff] Jpeg compressing a file", by Andrey Kiselev

What I want to do is take a TIFF file that is currently uncompressed and compress it using the jpeg compression schema. I know this is sorta possible because tiffcp does it but it creates a second file, I need to open a file, compress it, and close the file. Is this possible?

Of course, it is possible, but you can't read the header only. I mage data should be read too and written in the new file. It is not possible to compress the file in place.

So you should read data from the one file and write to another. There are two ways to do it: the simple one and the right one. The simple one illustrated by the attached source code. The right one is more complex and requires handling of arbitrary data types and data organization schemes (stripes and tiles). tiffcp implements the right way, that is why it is so complex.

Andrey

Andrey V. Kiselev
Home phone: +7 812 5274898 ICQ# 26871517

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

int main (int argc, char **argv)
{
    unsigned int i;
    TIFF *tif, *out;
    uint16 spp, bpp, photo;
    uint32 image_width, image_height, scansize;
    char *buf;

    if(argc < 3)
    {
        fprintf(stderr, "\nUSAGE: tiffcopy infile.tif outfile.tif\n");
        return 1;
    }

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

    out = TIFFOpen(argv[2], "w");
    if (!out)
    {
        fprintf (stderr, "Can't open %s for writing\n", argv[2]);
        return 3;
    }

    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &image_width);
    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &image_height);
    TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bpp);
    TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
    TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photo);
    scansize = TIFFScanlineSize(tif);
    buf = _TIFFmalloc(scansize * image_height);
    for (i = 0; i < image_height; i++)
        TIFFReadScanline(tif, buf + i * scansize, i, 0);

    TIFFSetField(out, TIFFTAG_IMAGEWIDTH, image_width);
    TIFFSetField(out, TIFFTAG_IMAGELENGTH, image_height);
    TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bpp);
    TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp);
    TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
    TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photo);
    TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
    TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, TIFFDefaultStripSize(out, 0));
    for (i = 0; i < image_height; i++)
        TIFFWriteScanline(out, buf + i * scansize, i, 0);

    _TIFFfree(buf);
    TIFFClose(out);
    TIFFClose(tif);

    return 0;
}