1

I need to read a .PBM image in binary (p4) for my school project.

I tried something like this:

for (int i = 0; i < img->height; i++)
{
    for (int x = 0; x < img->width; x++)
    {
        c = fgetc(fp);
        ungetc(c, fp);
        lum_val = fgetc(fp);
        /* Decode the image contents byte-by-byte. */
        for (k = 0; k < 8; k++) {
            printf("%d ", (lum_val >> (7 - k)) & 0x1);
            img->pixels[i][x].r = (lum_val >> (7 - k)) & 0x1;
            img->pixels[i][x].g = (lum_val >> (7 - k)) & 0x1;
            img->pixels[i][x].b = (lum_val >> (7 - k)) & 0x1;
        }
    }
    
}

based od this source code: https://github.com/nkkav/libpnmio/blob/master/src/pnmio.c but it doesn't work :( It only gives random 0 and 1 but not the way it is supposed to be.

  • 1
    What you meant by 'only gives 0 & 1' ? As the code is written, values of r,g,b will always be either 0 or 1 since you used AND operator with 0x1. – gobinda Nov 27 '20 at 12:25
  • The problem is that the image what i get isn't the same image as I want to read. (I mean it is a random binary image whit no sense to me) – Patrik Csikós Nov 27 '20 at 13:42

1 Answers1

1

I finally did it:

char b;
int i = 0;
int x = 0;
while (fread(&b, 1, 1, fp) == 1)
{
    for (int a = 0; a < 8; a++) {
        img->pixels[i][x].r = (b >> (7 - a)) & 0x1;
        img->pixels[i][x].g = (b >> (7 - a)) & 0x1;
        img->pixels[i][x].b = (b >> (7 - a)) & 0x1;
        x++;
        if (x == img->width) {
            x = 0;
            a = 8;
            if (i == img->height-1) {
                break;
            }
            else {
                i++;
            }
        }
        
    }
}