读入位图做纹理的程序,搞了小一阵。犯了些不该犯的错误,比如指针的指针。
另外发现a=a-b+(b=a)可以交换两个数值不用中间变量。C做的话没问题,C++却不行。所以下面代码还是用了中间变量。
位图像素是(B,G,R)存储的,所以得用最后个一while交换下两个值。
unsigned char * loadmytex(char *bmpname,int *bmpwidth ,int *bmpheight)
{
FILE *fp;
unsigned char tmpswap,*bmp;
long bmpsize;
if((fp=fopen(bmpname,"r"))==NULL)
{
printf("error,no pic be loaded/n");
getchar();
exit(1);
}
fseek(fp,18,SEEK_SET); //find the width information
fread(bmpwidth,4,1,fp); //read a unsigned long type (4 bytes) into bmpwidth
fread(bmpheight,4,1,fp); //read a unsigned long type (4 bytes) into bmpheight
bmpsize=(*bmpwidth)*(*bmpheight)*3;
if((bmp=(unsigned char *)malloc(bmpsize*sizeof(unsigned char)))==NULL)return 0;
fseek(fp,54,SEEK_SET); //find the bitmap data start offset (54)
fread(bmp,sizeof(unsigned char),bmpsize,fp);
fclose(fp);
while(bmpsize-=3){tmpswap=bmp[bmpsize];bmp[bmpsize]=bmp[bmpsize+2];bmp[bmpsize+2]=tmpswap;}//swap the red and blue partition
return bmp;
}