ファイルを読み込み,書き込む

サンプルは,ビットマップファイルを読み込み,そのまま,ファイル名を変えて,書き出す.
以下がそのサンプルコードだ.
ビットマップファイルの書き込みは,ここにある.

ReadBitmap("test01.bmp",&pixel,&width,&height);
WriteBitmap("test02.bmp",pixel, width, height);
free(pixel);

読み出し

int ReadBitmap(const char*pFilename, unsigned char **pPixel, int *nWidth, int *nHeight){
int			x,y;
FILE			*fp;
unsigned char*		bitdata;
BitmapHeader		header;
BitmapInfoHeader	info;
unsigned char		red,green,blue,dummy;
if( !( fp = fopen(pFilename, "rb") ))
return 0;
if( !ReadHeader(&header,fp) ){
fclose(fp);
return 0;
}
if( !ReadInfoHeader(&info,fp) ){
fclose(fp);
return 0;
}
#ifdef __ENDIAN		// Macのときは__ENDIANを定義し,エンディアン変換を行う.
SwapByteOrderHeaders(&header, &info);
#endif
// check header
if( !CheckHeaders(&header,&info) ){
fclose(fp);
return 0;
}
// calculate alignment size
int dataWidth = (header.m_nFilesize - header.m_nOffset)/info.m_nHeight;
int writeWidth = dataWidth - 3*info.m_nWidth;
// read pixels
bitdata = (unsigned char*)malloc(3*info.m_nWidth*info.m_nHeight*sizeof(unsigned char));
for(y=info.m_nHeight-1;y>=0;y--){
for(x=0;x<info.m_nWidth;x++){
fread( &blue, sizeof(unsigned char),1,fp);
fread( &green, sizeof(unsigned char),1,fp);
fread( &red, sizeof(unsigned char),1,fp);
// BGR->RGB
*(bitdata+3*(x+y*info.m_nWidth)  )  = red;
*(bitdata+3*(x+y*info.m_nWidth)+1)= green;
*(bitdata+3*(x+y*info.m_nWidth)+2)= blue;
}
for(x=0;x<writeWidth;x++){
fread( &dummy, sizeof(unsigned char),1,fp);
}
}
// return bitmap data
*nWidth = info.m_nWidth;
*nHeight= info.m_nHeight;
*pPixel = bitdata;
// file close
fclose(fp);
return 1;
}

サンプルコード

http://code.google.com/p/sonson-code/source/browse/#svn/trunk/src/bitmapSrc