(biwidth*biBitCount/8+3)/4*4

本文详细解释了在VC++中处理BMP图像时,如何使用特定的数学公式将每行字节数调整为4的倍数。通过具体的例子说明了该算法的工作原理及其在不同情况下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://wenda.tianya.cn/question/510127906cc5c480

在VC++中,读入BMP图像必须把每行所占的字节数转换为4的倍数,用了这个公式(biwidth*biBitCount/8+3)/4*4,不明白其含义

注意:C语言的除法里,两个int相除,结果会被CUT掉——只取商而不取余数。
biwidth*biBitCount/8 好理解,就是一个扫描行的字节数(如:100 * 24/8,即100 * 3 ,有100个像素,每个像素有3个字节,所以每行总字节数为300)
记 b = biwidth*biBitCount/8,  那么, 原式 =(b+3)/4*4,
情况一,b是四的倍数,(b+3)/4*4 == (b/4*4 + 3/4*4) == b + 0 == b

(如上:300是4的倍数,所以(300+3)/4*4 == (300/4*4)+3/4*4 == 75*4+(3/4*4)(因C程序里两个int相除,只取整数所以3/4*4等于0 ),即结果为300 Bytes


情况二,b不是四的倍数
  另 b = 4x+n,其中4x就是x的4倍数,n就是那个余数。
  容易得知:1 <= n <= 3,   4 <= n+3 <= 6,
    于是,原式 ==  (4x+n + 3)/4*4, (其中x是任意值),
                       ==  (4x/4*4 + (n+3)/4*4)
    在C语言中  ==   4x + 4  == (x+1)*4
例如:
1. (16)/4*4 == 16, 
2. (18+3)/4*4 == (16+2+3)/4*4 == (16 + 5)/4*4 == (4+1)*4 == 20

   (33+3)/4*4 == (32+1+3)/4*4 == (32 + 4)/4*4 == (8+1)*4 == 36
   (34+3)/4*4 == (32+2+3)/4*4 == (32 + 5)/4*4 == (8+1)*4 == 36
   (35+3)/4*4 == (32+3+3)/4*4 == (32 + 6)/4*4 == (8+1)*4 == 36

写出下面代码的伪代码并作出解释: 这是一个图片反色代码 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #pragma pack(1) typedef struct { unsigned short bfType; unsigned int bfSize; unsigned short bfReserved1; unsigned short bfReserved2; unsigned int bfOffBits; } BITMAPFILEHEADER; typedef struct { unsigned int biSize; unsigned int biWidth; unsigned int biHeight; unsigned short biPlanes; unsigned short biBitCount; unsigned int biCompression; unsigned int biSizeImage; unsigned int biXPelsPerMeter; unsigned int biYPelsPerMeter; unsigned int biClrUsed; unsigned int biClrImportant; } BITMAPINFOHEADER; void* ReadBMP(const char* filename, BITMAPINFOHEADER* bmpHeader); //将原始BMP图像文件名和反色处理后的图像文件名作为参数,完成反色功能 int revers_bmp_color(const char* orig_filename, const char * new_filename) { FILE * fd = fopen(orig_filename, "rb"); if(fd == NULL) { fclose(fd); return 0; } BITMAPFILEHEADER bfh; BITMAPINFOHEADER bih; //读入文件头 fread(&bfh, sizeof(BITMAPFILEHEADER), 1, fd); fread(&bih, sizeof(BITMAPINFOHEADER), 1, fd); int byteperline = (bih.biWidth * bih.biBitCount / 8 + 3) / 4 * 4; int size = byteperline * bih.biHeight; unsigned char* data = (unsigned char*)malloc(size); fread(data, (bfh.bfSize - bfh.bfOffBits), 1, fd); for (int i = 0; i < size; i++) { data[i] = ~data[i]; //反色 } //写入新文件 FILE* newfd = fopen(new_filename, "wb"); fwrite(&bfh, sizeof(BITMAPFILEHEADER), 1, newfd); fwrite(&bih, sizeof(BITMAPINFOHEADER), 1, newfd); fwrite(data, size, 1, newfd); fclose(newfd); free(data); fclose(fd); return 0; } int main() { revers_bmp_color("jjb.bmp", "jjb2.bmp"); return 0; }
02-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值