www.pudn.com > OBJReadandRender.rar > loadtex.cpp, change:2009-06-16,size:1976b


 
#include "stdafx.h" 
#include "loadtex.h" 
 
unsigned char *LoadTGAFile( char * strFilename,	tTGAHeader_s *header) 
{ 
/// 局部变量 /////////////////////////////////////////////////////////// 
	short			BPP; 
	unsigned char	*buffer; 
	int bitsize;		    // bitmap文件的大小 
	BYTE	*newbits;		// New RGB bits  
	BYTE	*from, *to;		// RGB looping vars 
	int		i, j,			// Looping vars */ 
	width;			        // Aligned width of bitmap  
    FILE* file; 
/////////////////////////////////////////////////////////////////////////////// 
 
    // 打开文件并且读取其头文件 
	file = fopen( strFilename, TEXT("rb") ); 
    if( NULL == file ) 
        return NULL; 
 
    if ( fread( header, sizeof( tTGAHeader_s ), 1, file ) != 1 ) 
    { 
        fclose( file ); 
        return NULL; 
    } 
 
    DWORD dwWidth, dwHeight; 
	dwWidth = (DWORD)header->d_width; 
	dwHeight = (DWORD)header->d_height; 
	BPP = (short)header->d_pixel_size;          // 16, 24, or 32 
 
	// JL TEST SMALL TEXTURES ONLY 
//	dwWidth = 2; 
//	dwHeight = 2; 
    // 创建一个bitmap文件,并将数据导入 
 
	bitsize = dwWidth * dwHeight * (BPP/8); 
	if ((newbits = (BYTE *)calloc(bitsize, 1)) == NULL) 
	{ 
        fclose( file ); 
        return NULL; 
	} 
 	buffer = (unsigned char *)malloc(dwWidth*dwHeight*(BPP / 8)); 
    if ( fread( buffer, dwWidth*dwHeight*(BPP / 8), 1, file ) != 1 ) 
	{ 
        fclose( file ); 
		free(buffer); 
		free(newbits); 
        return NULL; 
	} 
 
	width   = (BPP / 8) * dwWidth; 
 
    for (i = 0; i  dwHeight; i ++) 
		for (j = 0, from = ((BYTE *)buffer) + i * width, 
	        to = newbits + i * width; 
			j  dwWidth; 
			j ++, from += (BPP / 8), to += (BPP / 8)) 
        { 
				if (BPP == 24) 
				{ 
					to[0] = from[2]; 
					to[1] = from[1]; 
					to[2] = from[0]; 
				} 
				else 
				{ 
					to[0] = from[0]; 
					to[1] = from[1]; 
					to[2] = from[2]; 
					to[3] = from[3]; 
				} 
        }; 
 
	free(buffer); 
    fclose( file ); 
 
    return newbits; 
}