现在的位置: 首页 > 综合 > 正文

C语言构建BMP文件(一)

2013年12月08日 ⁄ 综合 ⁄ 共 2277字 ⁄ 字号 评论关闭
#define false 0
#define true 0

typedef struct tagXSurface{
	u32 surface;
	int width,height;
	
	int pitchWidth,pitch;	
	u32 *pData;
}XSurface;

XSurface pDemoSurface;

typedef struct tag_bmp_data
{
	int width;
	int height;
}_bmp_data;

_bmp_data p_my_bmp_data;

FILE *pWritingFile = NULL; 

int WriteBmp(XSurface *pInputSurface,char *BmpFileName)
{
	int i=0,k=0;
	long j=0;
	int get_size;
	int write_cnt;
	char *pTempBuffer=NULL;
	int w=pInputSurface->width;
	int h=pInputSurface->height;
	char *pSurfaceData=(char *)(pInputSurface->pData);
	int EVERY_READ_SIZE=pInputSurface->pitchWidth*3;

	if((w!=p_my_bmp_data.width)||(h!=p_my_bmp_data.height))
	{
		JPRINTF(("Write BMP Failed, w( %d != %d ), h( %d != %d ) \n",w,p_my_bmp_data.width,h,p_my_bmp_data.height));
		return -1;
	}

	JPRINTF(("Offset:: %d \n",ftell(pWritingFile)));
	
	pTempBuffer=(char *)XMemAlloc(sizeof(char)*EVERY_READ_SIZE);
	if(NULL==pTempBuffer)
	{
		JPRINTF(("Malloc Memory Failed ... \n"));
		return -2;
	}


	
	get_size=EVERY_READ_SIZE;

	for(k=pInputSurface->height;k>=0;--k)
	{
		for(i=0,j=0+k*(pInputSurface->pitchWidth)*4;i<get_size;i+=3,j+=4)
		{
			pTempBuffer[i]=pSurfaceData[j];
			pTempBuffer[i+1]=pSurfaceData[j+1];
			pTempBuffer[i+2]=pSurfaceData[j+2];
		}
		write_cnt=fwrite(pTempBuffer, sizeof(char), get_size,  pWritingFile); 
		if(write_cnt!=get_size)
			JPRINTF(("### Write Error !###\n"));
	}

	fclose(pWritingFile);	
}

int CreateBmp(long w, long h, char *BmpFileName)
{ 

#define BMP_Header_Length 54 

	long ret;
	unsigned char header[BMP_Header_Length] = { 

		0x42, 0x4d, 0, 0, 0, 0, 0, 0, 0, 0, 

			54, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0, 

			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 

			0, 0, 0, 0 

	}; 

	long file_size = (long)w * (long)h * 3 + 54; 

	header[2] = (unsigned char)(file_size &0x000000ff); 

	header[3] = (file_size >> 8) & 0x000000ff; 

	header[4] = (file_size >> 16) & 0x000000ff; 

	header[5] = (file_size >> 24) & 0x000000ff; 

	long width = w; 

	header[18] = width & 0x000000ff; 

	header[19] = (width >> 8) &0x000000ff; 

	header[20] = (width >> 16) &0x000000ff; 

	header[21] = (width >> 24) &0x000000ff; 

	long height = h; 

	header[22] = height &0x000000ff; 

	header[23] = (height >> 8) &0x000000ff; 

	header[24] = (height >> 16) &0x000000ff; 

	header[25] = (height >> 24) &0x000000ff; 

	//FILE *pWritingFile = NULL; 

	pWritingFile = fopen(BmpFileName, "wb"); 
	if( pWritingFile == NULL )
		return false; 

	fwrite(header, sizeof(unsigned char), 54, pWritingFile);

	p_my_bmp_data.width=width;
	p_my_bmp_data.height=height;

	return true;	
}

void creat_snap(char *BmpFileName)
{
	CreateBmp(pDemoSurface->width,pDemoSurface->height,BmpFileName);
	WriteBmp(pDemoSurface,BmpFileName);
}

抱歉!评论已关闭.