home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Cutting-Edge 3D Game Programming with C++
/
CE3DC++.ISO
/
BOOK
/
CHAP03
/
TGA32.CPP
< prev
next >
Wrap
C/C++ Source or Header
|
1995-10-20
|
3KB
|
108 lines
//
// A class to read 256-color, uncompressed, TGA images
// in 32-bit mode.
//
// Written by John De Goes
//
#include <Dos.h>
#include <Conio.h>
#include <Iostream.h>
#include "Tga32.hpp"
int TGAHeader::Load(FILE *File)
{
// Read the entire header; return 1 if success, 0 if failure.
const int HeaderSize = sizeof(TGAHeader);
if (fread(this, HeaderSize, 1, File) != 1)
return 0;
return 1;
}
// Make sure data aligned at BYTE boundary!!!
int TGAImage::Load(char *FileName)
{
FILE *File;
// Open file in binary mode, abort if error detected:
if ((File = fopen(FileName, "rb")) == 0)
return 0;
// Load the header C++ style:
if (Header.Load(File) == 0)
return 0;
// Check for conditions we don't want to handle:
// Make sure image is uncompressed:
if (Header.ImageType != 1)
return 0;
// Make sure image is 256 colors:
if (Header.PixelBits != 8)
return 0;
// Make sure image has a 16M color palette:
if (Header.PaletteEntrySize != 24)
return 0;
// Check for ID string:
if (Header.IDLength > 0)
{
// If ImageID was previously initialized, unlock memory:
if ( ImageID )
delete [] ImageID;
// Allociate memory for string:
if ((ImageID = new BYTE[Header.IDLength]) == 0)
return 0;
// Read the ID string:
fread(ImageID, Header.IDLength, 1, File);
}
// If Palette was previously initialized, unlock memory:
if ( Palette )
delete [] Palette;
// Create the palette:
if ((Palette = new BYTE[3 * 256]) == 0)
return 0;
// Initialize misc. variables:
Width = Header.ImageWidth;
Height = Header.ImageHeight;
ImageSize = Width * Height;
// Load the palette, converting 24-bits to 8-bits:
for (int Index = 0; Index < 256; Index++)
for (int Color = 2; Color >= 0; --Color)
{
BYTE PaletteColor;
// Read a single palette number:
fread(&PaletteColor, 1, 1, File);
// Convert to 8-bit format:
PaletteColor >>= 2;
// Change palette entry:
Palette[Index * 3 + Color] = PaletteColor;
}
// If Image was previously initialized, unlock memory:
if ( Image )
delete [] Image;
// Allociate image memory:
if ((Image = new BYTE[ImageSize]) == 0) // Abort if error
return 0;
// Load the image:
fread(Image, ImageSize, 1, File);
// Close file:
fclose(File);
// Return success!
return 1;
}