/* * RgbImage.cpp * * Read an image from a bitmap (.bmp) file. The functionality is * encapsulated in a class, RgbImage. * * An RgbImage object holds an array of RGB values in byte format * Main functionality is to read an RGB image from a BMP (bitmap) file * The image data rows will be word aligned. * * Author: Samuel R. Buss * * Software accompanying the book. * 3D Computer Graphics: A Mathematical Introduction with OpenGL, * by S. Buss, Cambridge University Press, 2003. * * Software is "as-is" and carries no warranty. It may be used without * restriction, but if you modify it, please change the filenames to * prevent confusion between different versions. * Bug reports: Sam Buss, sbuss@ucsd.edu. * Web page: http://math.ucsd.edu/~sbuss/MathCG * */ #include "RgbImage.h" /* ******************************************************************** * LoadRgbBmp * Read into memory an RGB image from an uncompressed BMP file. * Return true for success, false for failure. Error code is available * with a separate call. **********************************************************************/ bool RgbImage::LoadBmpFile( const char* filename ) { Reset(); FILE* infile = fopen( filename, "rb" ); // Open for reading binary data if ( !infile ) { fprintf(stderr, "Unable to open file: %s\n", filename); ErrorCode = OpenError; return false; } bool fileFormatOK = false; int bChar = fgetc( infile ); int mChar = fgetc( infile ); if ( bChar=='B' && mChar=='M' ) { // If starts with "BM" for "BitMap" skipChars( infile, 4+2+2+4+4 ); // Skip 4 fields we don't care about NumCols = readLong( infile ); NumRows = readLong( infile ); skipChars( infile, 2 ); // Skip one field int bitsPerPixel = readShort( infile ); skipChars( infile, 4+4+4+4+4+4 ); // Skip 6 more fields if ( NumCols>0 && NumCols<=100000 && NumRows>0 && NumRows<=100000 && bitsPerPixel==24 && !feof(infile) ) { fileFormatOK = true; } } if ( !fileFormatOK ) { Reset(); ErrorCode = FileFormatError; fprintf(stderr, "Not a valid 24-bit bitmap file: %s.\n", filename); fclose ( infile ); return false; } // Allocate memory ImagePtr = new unsigned char[NumRows*GetNumBytesPerRow()]; if ( !ImagePtr ) { fprintf(stderr, "Unable to allocate memory for %ld x %ld bitmap: %s.\n", NumRows, NumCols, filename); Reset(); ErrorCode = MemoryError; fclose ( infile ); return false; } unsigned char* cPtr = ImagePtr; for ( int i=0; i