将纯净的摄像头RGB数据转为bmp

 利用VS2013使用C语言实现。

#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)

#pragma pack(1)//结构体字节对齐,必须有
typedef struct tagBITMAPFILEHEADER
{
	unsigned short    bfType;//2WORD
	unsigned short  bfReserved1;//2WORD
	unsigned long   bfSize;//4DWORD
	unsigned long   bfOffBits;//4DWORD
	unsigned short    bfReserved2;//2WORD
} BITMAPFILEHEADER;

typedef struct tagBITMAPINFOHEADER
{
	unsigned long biSize;
	unsigned long biWidth;
	unsigned long biHeight;
	unsigned short biPlanes;
	unsigned short biBitCount;
	unsigned long biCompression; 
	unsigned long biSizeImage; 
	unsigned long biXPelsPerMeter; 
	unsigned long biYPelsPerMeter; 
	unsigned long biClrUsed;
	unsigned long biClrImportant;
}BITMAPINFOHEADER;

bool saveBmp(char *bmpName, unsigned char *imgBuf, int width, int height,
	int biBitCount)
{
	//如果位图数据指针为0,则没有数据传入,函数返回
	if (!imgBuf)
		return 0;

	//颜色表大小,以字节为单位,灰度图像颜色表为1024字节,彩色图像颜色表大小为0
	int colorTablesize = 0;
	if (biBitCount == 8)
		colorTablesize = 1024;

	//待存储图像数据每行字节数为4的倍数
	int lineByte = (width * biBitCount / 8 + 3) / 4 * 4;

	//以二进制写的方式打开文件
	FILE *fp = fopen(bmpName, "wb");
	if (fp == 0) return 0;

	//申请位图文件头结构变量,填写文件头信息
	BITMAPFILEHEADER fileHead;
	fileHead.bfType = 0x4D42;//bmp类型

	//bfSize是图像文件4个组成部分之和
	fileHead.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)
		+ colorTablesize + lineByte*height;
	
	fileHead.bfReserved1 = 0;
	fileHead.bfReserved2 = 0;
	
	//bfOffBits是图像文件前三个部分所需空间之和
	fileHead.bfOffBits = 54 + colorTablesize;

	//写文件头进文件
	fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);

	//申请位图信息头结构变量,填写信息头信息
	BITMAPINFOHEADER head;
	head.biBitCount = biBitCount;
	head.biClrImportant = 0;
	head.biClrUsed = 0;
	head.biCompression = 0;
	head.biHeight = height;
	head.biPlanes = 1;
	head.biSize = 40;
	head.biSizeImage = lineByte*height;
	head.biWidth = width;
	head.biXPelsPerMeter = 0;
	head.biYPelsPerMeter = 0;
	//写位图信息头进内存
	fwrite(&head, sizeof(BITMAPINFOHEADER), 1, fp);

	//写位图数据进文件
	fwrite(imgBuf, height*lineByte, 1, fp);

	//关闭文件
	fclose(fp);

	return 1;
}
int main()
{
	unsigned char *buf = (unsigned char *)malloc(640 * 480 * 3);
	FILE *fpR = NULL;
	FILE *fpW = NULL;
	fpR = fopen("640-480.rgb", "rb");/*640 * 480 rgb无压缩数据*/
	if (fpR == NULL)
	{
		printf("Read file failed ! \n");
		exit(1);
	}	
	fread(buf, 640 * 480 * 3, 1, fpR);

	saveBmp("69.bmp", buf, 640, 480, 24);
	system("pause");
	return 0;
	
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值