0

我需要为我的学校项目读取二进制 (p4) 格式的 .PBM 图像。

我试过这样的事情:

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

基于 od 此源代码:https ://github.com/nkkav/libpnmio/blob/master/src/pnmio.c 但它不起作用:(它只给出随机 0 和 1 但不是它应该的方式是。

4

1 回答 1

0

我终于做到了:

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++;
            }
        }
        
    }
}
于 2020-11-27T14:13:01.510 回答