unit LibTiffDelphiHigherLevel;

interface

uses
  Windows, SysUtils, Classes, Graphics, Controls, Forms, LibTiffDelphi,
  ExtCtrls;

{uses LibTiffDelphi, download it here:
     http://www.awaresystems.be/imaging/tiff/delphi.html }

function ReadTIFFFileIntoBitmap(Filename: String): TBitmap;
procedure VisualizeTIFFFileInImage(Filename: String; Image: TImage);

implementation

procedure TIFFReadRGBAImageSwapRB(Width,Height: Cardinal; Memory: Pointer);
forward;

procedure TIFFReadRGBAImageSwapRB(Width,Height: Cardinal; Memory: Pointer);
{$IFDEF DELPHI_5}
type
  PCardinal = ^Cardinal;
{$ENDIF}
var
  m: PCardinal;
  n: Cardinal;
  o: Cardinal;
begin
  m:=Memory;
  for n:=0 to Width*Height-1 do
  begin
    o:=m^;
    m^:= (o and $FF00FF00) or                {G and A}
        ((o and $00FF0000) shr 16) or        {B}
        ((o and $000000FF) shl 16);          {R}
    Inc(m);
  end;
end;

function ReadTIFFFileIntoBitmap(Filename: String): TBitmap;
var
  OpenTiff: PTIFF;
  FirstPageWidth,FirstPageHeight: Cardinal;
  FirstPageBitmap: TBitmap;
begin
  OpenTiff:=TIFFOpen(Filename,'r');
  if OpenTiff=nil then raise Exception.Create(
           'Unable to open file '''+Filename+'''');
  TIFFGetField(OpenTiff,TIFFTAG_IMAGEWIDTH,@FirstPageWidth);
  TIFFGetField(OpenTiff,TIFFTAG_IMAGELENGTH,@FirstPageHeight);
  FirstPageBitmap:=nil;
  try
    FirstPageBitmap:=TBitmap.Create;
    FirstPageBitmap.PixelFormat:=pf32bit;
    FirstPageBitmap.Width:=FirstPageWidth;
    FirstPageBitmap.Height:=FirstPageHeight;
  except
    if FirstPageBitmap<>nil then FirstPageBitmap.Destroy;
    TIFFClose(OpenTiff);
    raise Exception.Create('Unable to create TBitmap buffer');
  end;
  TIFFReadRGBAImage(OpenTiff,FirstPageWidth,FirstPageHeight,
               FirstPageBitmap.Scanline[FirstPageHeight-1],0);
  TIFFClose(OpenTiff);
  TIFFReadRGBAImageSwapRB(FirstPageWidth,FirstPageheight,
               FirstPageBitmap.Scanline[FirstPageHeight-1]);
  Result:=FirstPageBitmap;
end;

procedure VisualizeTIFFFileInImage(Filename: String; Image: TImage);
var
  m: TBitmap;
begin
  try
    m:=ReadTIFFFileIntoBitmap(Filename);
    Image.Picture.Assign(m);
    m.Destroy;
  except
    Image.Picture.Assign(nil);
  end;
end;

end.
