问题描述
我正在制作一个用 C 语言创建位图文件的程序.它使用 24 位颜色.
I'm making a program that creates a bitmap file in C. it's using 24-bit colour.
我分 3 个阶段编写文件,我首先编写 FileHeader,然后是 InfoHeader,然后是像素数据.我在填充像素数据时遇到问题,因此每行都在字边界上结束.
I'm writing the file in 3 stages, i first write the FileHeader, then the InfoHeader, and then the Pixel Data. I'm having trouble padding the pixel data so each row finishes on a word boundary.
下面的代码有时有效,但只是没有while循环(它将填充添加到行尾).例如,对于 12x12 像素的图像,我可以将其缩放到 24x24,但不能缩放到 10x10(文件已损坏).当我输入下面的填充代码时,图像会变形,有时也会损坏.
The code below works sometimes, but only without the while loop (which adds the padding to the end of the line). For example, with a 12x12px image, I can scale it to 24x24, but not to 10x10 (the file is corrupt). When I put in the padding code below, the image becomes distorted, and sometimes gets corrupted too.
我似乎无法弄清楚出了什么问题,下面的代码应该在每行的末尾添加填充,直到遇到单词边界,然后开始下一行.
I can't seem to figure out what's going wrong, the code below should add padding to the end of each line until i hits a word boundary, and then starts the next line.
fwrite(&fh, 1, sizeof(FILEHEADER), n_img);
fwrite(&ih, 1, sizeof(INFOHEADER), n_img);
int i, j;
uint8_t pad = 0;
for (i = height-1; i >= 0; i--) {
for (j = 0; j < width; j++)
fwrite(n_pix+(i*width)+j, 1, sizeof(IMAGE), n_img);
while(ftell(n_img)%4 != 0)
fwrite(&pad, 1, 1, n_img);
}
推荐答案
您不是将行填充到文字大小,而是将当前文件位置填充.它不起作用,因为标题的大小加起来是 54 —— 不是 4 的倍数.
You are not padding rows to word size, you are padding the current file position. And it doesn't work because the size of your headers add up to 54 -- not a multiple of 4.
不要使用 ftell 来检索当前位置",而是使用数学.使您的 pad
成为无符号长整型,并在循环之前插入:
Instead of using ftell to retrieve the 'current position', use maths. Make your pad
an unsigned long, and insert before your loops:
int npad = (sizeof(IMAGE)*width) & 3;
if (npad)
npad = 4-npad;
然后,立即写出所需字节数,而不是 while(ftell ..
循环:
Then, instead of the while(ftell ..
loop, write out the number of required bytes immediately:
fwrite (&pad, 1,npad, n_img);
npad
的范围为 0..3,这就是为什么您必须将 pad
设为 4 字节整数.
npad
will range from 0..3, that's why you have to make pad
a 4-byte integer.
这篇关于填充位图像素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!