delphitiffdelphi-xe2

How to load and display tiff images in TImage control?


I am currently working on Delphi XE2 trial version. I want to load and display TIFF images in TImage control without using any third party component/library.

I tried below code but it is not woking for me.

Procedure TForm1.Button1Click(Sender: TObject); 
Var 
     OleGraphic               : TOleGraphic; 
     fs                       : TFileStream; 
     Source                   : TImage; 
     BMP                      : TBitmap; 
Begin 
     Try 
          OleGraphic := TOleGraphic.Create; 

          fs := TFileStream.Create('c:\testtiff.dat', fmOpenRead Or fmSharedenyNone); 
          OleGraphic.LoadFromStream(fs); 

          Source := Timage.Create(Nil); 
          Source.Picture.Assign(OleGraphic); 

          BMP := TBitmap.Create; 
          bmp.Width := Source.Picture.Width; 
          bmp.Height := source.Picture.Height; 
          bmp.Canvas.Draw(0, 0, source.Picture.Graphic); 

          image1.Picture.Bitmap := bmp;
     Finally 
          fs.Free; 
          OleGraphic.Free; 
          Source.Free; 
          bmp.Free; 
     End; 
End;

Please advice.


Solution

  • As said in my comment, if the file extension is the standard tiff extension the code to open the file is trivial :

    image1.Picture.LoadFromFile(MyTiffFile);
    

    If not, follow the answer from dwrbudr.

    Here is an example :

    procedure LoadBitmapFromFile( aImage : TImage; tiffFilename : String);
    var
      tiffIm : TWICImage;
      ext : String;
    begin
      ext := SysUtils.ExtractFileExt(tiffFilename);
      if (ext = '.tif') or (ext = '.tiff')
        then aImage.Picture.LoadFromFile(tiffFilename)
        else begin
          tiffIm:= TWICImage.Create;
          try
            tiffIm.LoadFromFile(tiffFilename);
            aImage.Picture.Bitmap.Assign(tiffIm);
          finally
            tiffIm.Free;
          end;
        end;
    end;
    

    See also TWICImage, which works for XP SP3 and up.