24位RGB位图转换成1位位图

1位位图数据,每个像素点只有一个bit,0 or 1,0表示图像中的0,1表示255,在保存位图的时候需要在颜色表中指出。

unsigned char*  BMP24TOBMP1(unsigned char* img, int width, int height)
{
	int src_row_bytes;
	int dst_row_bytes;
	unsigned char* dst=NULL;
	unsigned char* ptr;
	unsigned char* p;

	int offset;
	int i;
	int j;
	int k;
	int gap;
    unsigned int size;

	int dst_width;
	int dst_height;

	src_row_bytes = (width * 3 + 3) & ~3;
	dst_row_bytes = ((width >> 3) + 3) & ~3;
	gap = src_row_bytes - width * 3;
	size = dst_row_bytes * height;
	dst = (unsigned char*)malloc(size);
	if(!dst)
		return NULL;
	unsigned int pxl;
    memset(dst, 0, size);

	ptr = img;
	p = dst;
	dst_height = height;
	dst_width = (width + 7) >> 3;
    
	for(i = 0; i < dst_height; i++)
	{   
		offset = 0;
		for(j = 0; j < dst_width; j++)
		{   
			pxl = 0;
			for(k = 7; k >= 0;k--)
			{
				if(*ptr > 128)
				{
					pxl = pxl | (0x01 << k);
				}
				ptr += 3;
				offset += 1;
				if(offset >= width)
					break;
			}
			p[i * dst_row_bytes + j] = pxl;
		}
		ptr+=gap;
	}

	return dst;
}


保存1位位图:

void WriteBMP1(unsigned char* data, char* fileName, int width,int height)
{
	BitmapFileHeader fileHead;
	BitmapHeader head;
	RGBQUAD1 quad[2];
	int colorTablesize;
	FILE *file = NULL;
	int rowBytes;
	int offset;

	rowBytes = ((width >> 3) + 3) &~3;
	colorTablesize = 8;

	//申请位图文件头结构变量,填写文件头信息
	fileHead.bfType = 0x4D42;//bmp类型
	//bfSize是图像文件4个组成部分之和
	fileHead.bfSize= sizeof(BitmapFileHeader) + sizeof(BitmapHeader)+ colorTablesize + rowBytes* height;
	fileHead.bfReserved1 = 0;
	fileHead.bfReserved2 = 0;
	//bfOffBits是图像文件前3个部分所需空间之和
	fileHead.bfOffBits=54+colorTablesize;
	//写文件头进文件
	memcpy(data, &fileHead, sizeof(BitmapFileHeader));
	//申请位图信息头结构变量,填写信息头信息
	offset = sizeof(BitmapFileHeader);

	head.biBitCount= 1;
	head.biClrImportant=0;
	head.biClrUsed=0;
	head.biCompression=0;
	head.biHeight= height;
	head.biPlanes=1;
	head.biSize=40;
	head.biSizeImage= rowBytes * height;
	head.biWidth= width;
	head.biXPelsPerMeter=2834;
	head.biYPelsPerMeter=2834;
	//写位图信息头进内存
	//fwrite(&head, sizeof(BitmapHeader),1, file);
	memcpy(data + offset, &head, sizeof(BitmapHeader));
	offset += sizeof(BitmapHeader);

	//如果灰度图像,有颜色表,写入文件 

	quad[0].rgbBlue = 0;
	quad[0].rgbGreen = 0;
	quad[0].rgbRed = 0;
	quad[0].rgbReserved = 0;

	memcpy(data + offset, &quad[0], sizeof(RGBQUAD1));
	offset += sizeof(RGBQUAD1);
	quad[1].rgbBlue = 255;
	quad[1].rgbGreen = 255;
	quad[1].rgbRed = 255;
	quad[1].rgbReserved = 0;

	memcpy(data + offset,&quad[1],sizeof(RGBQUAD1));
	file = fopen(fileName, "wb");
	if(!file)
		return;
	int len = fwrite(data, fileHead.bfSize, 1, file);
	fclose(file);
}

1位bmp图片需要写入颜色表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值