0

i'm struggling trying to figure out how to store pixels n times to an array

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

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

        // write RGB triple n times  to  array
        for (int k = 0; k < n; k++ )
        {
            fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
            scanline[k] = triple;
        }

    }

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

    // write array n times
    for (int j = 0; j < n; j++)
    {
       fwrite(scanline, sizeof(RGBTRIPLE), newwidth, outptr);
    }

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

}
1

I assume you declared RGBTRIPLE scanline[newwidth];, so that all the pixels actually fit in. Allocating on heap like RGBTRIPLE *scanline = malloc(newwidth * sizeof(RGBTRIPLE)); would work too, but require a free(scanline); later while providing no benefit, so I prefer the array.

You assign to scanline[k], those are the same n output pixels for each input pixel. You should advance by n per input pixel (so that you continue where you left the last time), for example by assigning to scanline[j * n + k] instead. Alternatively, you could have a counter initialised to 0 per input line, and increment it on assignment (like scanline[pos++] = triple;).

BTW, you write n+1 lines. I'd remove the fwrite from the reading loop. Also, you write output padding once per input line. You should write it once per output line.

2
  • yes i already fixed the padding issue, and about writing n times to the array, my code now works perfectly using scanline[ j * n + k] but could you please explain it more, i didn't get why we are adding k and thank you so much for replying
    – samia
    Nov 6 '19 at 18:17
  • We need k in the range from 0 to n-1 to address the n copies of the current pixel. And j*n describes the index of the first copy of the jth input pixel.
    – Blauelf
    Nov 7 '19 at 9:48

You must log in to answer this question.

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