Title: Viewing Targa Bitmap File Format in Delphi (256-colors)
Question: How to view Bitmap in Targa File Format (*.tga) using Delphi ?
Answer:
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:
const
FERRORMSG2 = 'Sorry, Unsupported Compressed(RLE) File Format';
FERRORMSG3 = 'Sorry, Unsupported More Than 256 Colours File Format';
type
TArrBuff = Array [1..512] of Byte;
TPalette_Cell = Record
b2, g2, r2 : byte;
End;
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;
end;
var
pal: TPPal;
pFile: File;
buffer: TArrBuff;
FTgaHeader: TTGA_Header;
procedure THPTGA.ReadImageData2Bitmap;
var
i, j, idx : integer;
begin
Seek(pFile, sizeof(FtgaHeader)+FtgaHeader.IDLength+768);
for i:=FtgaHeader.Height-1 downto FtgaHeader.YAwal do
begin
BlockRead(pFile, buffer, FtgaHeader.Width);
for j:=FtgaHeader.XAwal to FtgaHeader.Width-1 do begin
idx := j - FtgaHeader.XAwal + 1;
SetPixel(Bitmap.Canvas.Handle, j, i, rgb(pal^[buffer[idx]].r2, pal^[buffer[idx]].g2, pal^[buffer[idx]].b2));
end;
end;
end;
procedure THPTGA.LoadFromFile(const FileName: string);
begin
AssignFile(pFile, FileName);
{$I-} Reset(pFile, 1); {$I+}
if (IOResult = 0) then begin
try
BlockRead(pFile, FtgaHeader, SizeOf(FtgaHeader));
// checking unsupported features here
if (FtgaHeader.ImageType3) then begin
MessageBox(Application.Handle, FERRORMSG2, 'TGA Viewer Error', MB_ICONHAND);
exit;
end;
if (FtgaHeader.BpPixel8) then begin
MessageBox(Application.Handle, FERRORMSG3, 'TGA Viewer Error', MB_ICONHAND);
exit;
end;
GetMem(pal, 768);
try
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);
ReadImageData2Bitmap;
finally
FreeMem(pal);
end;
finally
CloseFile(pFile);
end;
end
else MessageBox(Application.Handle, 'Error Opening File', 'TGA Viewer Error', MB_ICONHAND);
end;
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.