数据结构:
BITMAPINFO bitmapInfo;
BITMAPFILEHEADER bitmapHeadInfo;
struct tagRGB
{
unsigned char R;
unsigned char G;
unsigned char B;
};
读取:
void ReadBitMap(const char* fileFulPath,tagRGB** arrayRGB,int &width,int &height)
{
FILE *pFile = fopen(fileFulPath, "rb");
if(pFile)
{
size_t size = 0;
/*BITMAPFILEHEADER BmpFileHeader;*/
memset( &bitmapHeadInfo,0,sizeof(BITMAPFILEHEADER));
size = fread(&bitmapHeadInfo,1,sizeof(BITMAPFILEHEADER),pFile);
//BITMAPINFO bitmapInfo;
memset( &bitmapInfo , 0 , sizeof(BITMAPINFO) ) ;
size = fread(&bitmapInfo,1, sizeof(BITMAPINFO),pFile);
width = bitmapInfo.bmiHeader.biWidth;
height =bitmapInfo.bmiHeader.biHeight;
fseek( pFile, bitmapHeadInfo.bfOffBits, 0 );
*arrayRGB = new tagRGB[width*height] ;
memset(*arrayRGB,0,sizeof(tagRGB)*width*height);
unsigned char buf[3] ={0};
for (int i=0; i<height; i++)
{
for (int j=0; j<width;j++)
{
size = fread(&((*arrayRGB)[i*width+j].B) , sizeof(unsigned char), 1, pFile ) ;
if (!size)
{
assert(0);
}
size = fread(&((*arrayRGB)[i*width+j].G) , sizeof(unsigned char), 1, pFile ) ;
if (!size)
{
assert(0);
}
size = fread(&((*arrayRGB)[i*width+j].R) , sizeof(unsigned char), 1, pFile ) ;
if (!size)
{
assert(0);
}
}
if (width%4 != 0)
{
fread( buf, sizeof(unsigned char)*width%4,1,pFile);
}
}
fclose(pFile);
pFile = NULL;
}
}
写入:
void WirteBitMap(const char* fileFulPath,tagRGB* arrayRGB,int width,int height)
{
FILE *fp1 = 0;
int ni = 0;
int nj = 0;
size_t size = 0;
if ( fileFulPath == NULL )
{
printf( "[WirteBitMap]:please enter right file name \n" );
return ;
}
if ( NULL == arrayRGB)
{
printf( "[WirteBitMap]:the data is wrong! \n" );
return ;
}
fp1 = fopen( fileFulPath, "wb" );
if ( fp1 == NULL )
{
printf( "[SaveBmp]:open file false\n" );
return ;
}
size = fwrite( &bitmapHeadInfo, sizeof(bitmapHeadInfo), 1, fp1 );
size = fwrite( &bitmapInfo, sizeof(bitmapInfo), 1, fp1 );
fseek( fp1, bitmapHeadInfo.bfOffBits, 0 );
unsigned char temp = 0;
for (int i=0; i<height; i++)
{
for (int j=0; j<width;j++)
{
size = fwrite(&(arrayRGB[i*width+j].B) , sizeof(unsigned char), 1, fp1 ) ;
if (!size)
{
assert(0);
}
size = fwrite(&(arrayRGB[i*width+j].G) , sizeof(unsigned char), 1, fp1 ) ;
if (!size)
{
assert(0);
}
size = fwrite(&(arrayRGB[i*width+j].R) , sizeof(unsigned char), 1, fp1 ) ;
if (!size)
{
assert(0);
}
}
if (width%4 != 0)
{
fwrite(&temp, sizeof(unsigned char),width%4,fp1);
}
}
fclose( fp1 );
fp1 = NULL;
}
实例:
int _tmain(int argc, _TCHAR* argv[])
{
tagRGB* arrayRGB = NULL;
int width = 0;
int heght = 0;
ReadBitMap("C:\\Users\\2012\\Desktop\\11.bmp",&arrayRGB,width,heght);
WirteBitMap("C:\\Users\\2012\\Desktop\\Test_dd.bmp",arrayRGB,width,heght);
return 0;
}