0

I understand why padding is necessary and how it works, but some 'experimenting' and comments left at the given code have made me question my understanding of padding.

    for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
{
    // iterate over pixels in scanline
    for (int j = 0; j < bi.biWidth; j++)
    {
        // temporary storage
        RGBTRIPLE triple;

        // read RGB triple from infile
        fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

        // write RGB triple to outfile
        fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
    }

    //skip over padding, if any
    fseek(inptr, padding, SEEK_CUR);

    //then add it back (to demonstrate how)
    for (int k = 0; k < padding; k++)
        fputc(0x00, outptr);

}

I experimented with a 3x3 pixel image small.bmp, so I had to add three padding bits. The comments say, that we skip over padding and then add it back, so it seems to me, that they are suggesting, that fseek() and the padding loop aren't necessary, but if I skipped them, the copied images last line came out grayish. I checked the bytes with xxd and it showed this:

0000036: 00ff00 00ff00 00ff00 000000  ............
0000042: 00ff00 ffffff 00ff00 000000  ............
000004e: 00ff00                       ...

So as I understand, the first two lines are as they should be (padded), but I have no Idea what is going on at the last line. I checked with debug50 if the loop somehow was cut short, but everything seemed fine. So my questions are:

  1. Is fseek() and the padding loop necessary in our code? (please explain the comments if so)
  2. Why the first two lines are padded, but the last one isn't?
  3. Why is there only one RGB triple in the last line and where did the rest go?
  4. Why is the whole last line grayish, if there is one pixel defined?
1

Yes, the fseek and padding loop are absolutely necessary.

Think about it mathematically. The image portion is composed of 36 bytes (3 lines with 3 3-byte pixels per line plus 3 bytes of padding per line). The i loop (height) will execute 3 times and the j loop (width) will execute three times (and read/write 9 bytes). For a total of 27 bytes. The output image is "missing" 9 bytes. Not by coincidence, those are the 9 bytes that would be "skipped" and "replaced" with the fseek and padding.

When viewed, the last line is "grayish" because it ran out of pixels.

The value of the comments will be become clear when you move on to resize, where you may not read and write the same number of padding bytes.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .