2005. április 17., vasárnap

Viewing Targa Bitmap File Format in Delphi (256-colors)


How to view Bitmap in Targa File Format (*.tga) using Delphi ?


This is quite simple way to answer above question: viewing Targa file format using Delphi (not compress and limited only 256 colors).

Here is the example code:

  FERRORMSG2 = 'Sorry, Unsupported Compressed(RLE) File Format';
  FERRORMSG3 = 'Sorry, Unsupported More Than 256 Colours File Format';

  TArrBuff = array[1..512] of Byte;
  TPalette_Cell = record
    b2, g2, r2: byte;
  TPal = array[0..255] of TPalette_Cell;
  TPPal = ^TPal;
  TTGA_Header = record // Targa(TGA) HEADER //
    IDLength, ColorMap, ImageType: byte;
    ClrMapSpes: array[1..5] of byte;
    XAwal, YAwal, Width, Height: SmallInt;
    BpPixel, ImageDescription: byte;

  pal: TPPal;
  pFile: file;
  buffer: TArrBuff;
  FTgaHeader: TTGA_Header;

procedure THPTGA.ReadImageData2Bitmap;
  i, j, idx: integer;
  Seek(pFile, sizeof(FtgaHeader) + FtgaHeader.IDLength + 768);
  for i := FtgaHeader.Height - 1 downto FtgaHeader.YAwal do
    BlockRead(pFile, buffer, FtgaHeader.Width);
    for j := FtgaHeader.XAwal to FtgaHeader.Width - 1 do
      idx := j - FtgaHeader.XAwal + 1;
      SetPixel(Bitmap.Canvas.Handle, j, i, rgb(pal^[buffer[idx]].r2,
        pal^[buffer[idx]].g2, pal^[buffer[idx]].b2));

procedure THPTGA.LoadFromFile(const FileName: string);
  AssignFile(pFile, FileName);
{$I-}Reset(pFile, 1);
  if (IOResult = 0) then
      BlockRead(pFile, FtgaHeader, SizeOf(FtgaHeader));
      // checking unsupported features here
      if (FtgaHeader.ImageType > 3) then
        MessageBox(Application.Handle, FERRORMSG2, 'TGA Viewer Error', MB_ICONHAND);
      if (FtgaHeader.BpPixel > 8) then
        MessageBox(Application.Handle, FERRORMSG3, 'TGA Viewer Error', MB_ICONHAND);
      GetMem(pal, 768);
        Bitmap.Width := FtgaHeader.Width;
        Bitmap.Height := FtgaHeader.Height;
        // if use Color-Map and Uncompressed then read it
        if (FtgaHeader.ImageType = 1) then
          BlockRead(pFile, pal^, 768);
    MessageBox(Application.Handle, 'Error Opening File', 'TGA Viewer Error',

How to try this code ?? Just call the "LoadFromFile" procedure above in your application (probably with little modification offcourse, especially about the name of mainForm that I used here [THPTGA]).

Hopefully It can help you.

For full source code and simple application that use this, you can look and download from my website: www.geocities.com/h4ryp/delphi.html.

Note: At http://www.delphi-gems.com/Graphics.php you can download the freeware Delphi unit GraphicEx.pas which makes a bunch of graphics formats available to Delphi programs, among them PCX, TIFF, TGA, etc. The formats are embedded into Delphi in the same way as Borland's jpeg unit.

Nincsenek megjegyzések:

Megjegyzés küldése