Search code examples
cimagepbmnetpbm

How to read .PBM binary in C


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.


Solution

  • 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++;
                }
            }
            
        }
    }