填充位图像素阵列 [英] Padding a Bitmap pixel array

查看:163
本文介绍了填充位图像素阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做在C.创建一个位图文件它使用24位颜色的程序。

我在写文件中的3个阶段,我先写FileHeader里,那么InfoHeader,然后像素数据。我无法填充的像素数据使每一行字边界结束。

下面作品的code 有时的,而只是没有while循环(这增加填充到行的结尾)。例如,用一个12x12px图像,我可以扩展到24×24,而不是10×10(文件已损坏)。当我把下面的填充code,图像扭曲,有时还会被损坏了。

我似乎无法弄清楚发生了什么事情不对劲,code以下应添加填充到每一行的末尾,直到我碰到一个单词边界,然后开始下一行。

  FWRITE(安培; FH,1,sizeof的(FileHeader里),n_img);
FWRITE(安培; IH,1,sizeof的(INFOHEADER),n_img);
INT I,J;
uint8_t有垫= 0;
对于(I =身高1; I> = 0;我 - ){
    为(J = 0; J<宽度; J ++)
        FWRITE(n_pix +(I *宽)+ J,1,sizeof的(IMAGE),n_img);    而(FTELL(n_img)%4!= 0)
        的fwrite(&放大器;垫,1,1,n_img);
}


解决方案

您不填充的的为字,你是在填充的当前文件位置的。而且它不工作,因为你的头的大小加起来54 - 不是4的倍数

而不是使用FTELL检索当前位置,用数学的。让你的无符号长,你的循环之前插入:

  INT NPAD =(sizeof的(IMAGE)*宽)及3;
如果(NPAD)
  NPAD = 4- NPAD;

然后,而不是而(FTELL .. 循环,马上写出来所需的字节数:

  FWRITE(放大器;垫,1,NPAD,n_img);

NPAD 将范围从0..3,这就是为什么你必须让一个4字节整数

I'm making a program that creates a bitmap file in C. it's using 24-bit colour.

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.

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);
}

解决方案

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.

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;

Then, instead of the while(ftell .. loop, write out the number of required bytes immediately:

fwrite (&pad, 1,npad, n_img);

npad will range from 0..3, that's why you have to make pad a 4-byte integer.

这篇关于填充位图像素阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆