Tiff Sample

This sample shows how to read and write a tiff image.

using Tiff;
using GLib;

public class TiffReadWrite : Object {

    private uint32[] raster;
    private uint32 width;
    private uint32 height;
    private uint32 size;

    private string fname { get ; set; }
    private string fmode { get; set; }

    public TiffReadWrite (string filename, string mode) {
        this.fname = filename;
        this.fmode = mode;
    }

    public void read_image () {

        var tif = new TIFF (fname, fmode);

        if (tif == null) {
            error ("Couldn't open file %s\n", fname);
        }

        tif.GetField (TIFFTAG_IMAGEWIDTH, out this.width);
        tif.GetField (TIFFTAG_IMAGELENGTH, out this.height);
        this.size = this.width * this.height;

        raster = new uint32[size];
        if (!tif.ReadRGBAImage (this.width, this.height, this.raster, 0)) {
            error ("Couldn't read image %s!\n", this.fname);
        }
    }

    public void write_image (string filename) {
        var newtif = new TIFF (filename, "w");
        var row = new uint8[width];

        newtif.SetField (TIFFTAG_IMAGEWIDTH, this.width);
        newtif.SetField (TIFFTAG_IMAGELENGTH, this.height);
        newtif.SetField (TIFFTAG_BITSPERSAMPLE, 8);
        newtif.SetField (TIFFTAG_COMPRESSION, COMPRESSION_LZW);
        newtif.SetField (TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
        newtif.SetField (TIFFTAG_ORIENTATION, ORIENTATION_BOTLEFT);

        for (uint32 h = 0; h < this.height; h++) {
            for (uint32 w = 0; w < this.width; w++) {
                row[w] = (uint8) raster[this.width * h + w];
            }
            newtif.WriteScanline ((tdata_t) row, h, 0);
        }
    }

    public static int main (string[] args) {
        string in_arg = args[1];
        if (in_arg == null) {
            stderr.printf ("Argument required!\n");
            return 1;
        }

        var tt = new TiffReadWrite (in_arg, "r");

        tt.read_image ();
        tt.write_image ("/tmp/test.tiff");

        return 0;
    }
}

Compile and Run

$ valac --pkg tiff -X -ltiff -o tiffreadwrite TiffReadWrite.vala
$ ./tiffreadwrite


Vala/Examples

Projects/Vala/TiffSample (last edited 2013-11-22 16:48:26 by WilliamJonMcCann)