nz_21
nz_21

Reputation: 7343

C++ how to parse a ppm file?

I'm trying to parse a ppm file.

The spec is this: http://netpbm.sourceforge.net/doc/ppm.html

Example:


P3
# feep.ppm
4 4
15
 0  0  0    0  0  0    0  0  0   15  0 15
 0  0  0    0 15  7    0  0  0    0  0  0
 0  0  0    0  0  0    0 15  7    0  0  0
15  0 15    0  0  0    0  0  0    0  0  0

The stuff after the "15" are the rgb values of all pixels in the give image.

I have tried this so far:




void read_and_draw_ppm_file() {
    ifstream infile;
    infile.open(TEXTURE_FILE.c_str());
    string line;
    int count = 0;
    while (getline(infile, line) && count < 4) {
        count++;
    }


    char c;

    int red = -1, green = -1, blue = -1;
    int rgb_count = 0;
    for (int i = 0; i < TEXTURE_WIDTH; i++) {
        for (int j = 0; j < TEXTURE_HEIGHT; j++) {


              infile >> c;


            if (rgb_count == 0) {
                if (red != -1 && blue != -1 && green != -1) {
                    cout << red<<endl;
                    cout << green<<endl;
                    cout << blue<<endl;


                    uint32_t colour = (255 << 24) + (int(red) << 16) + (int(green) << 8) + int(blue);
                    window.setPixelColour(i, j, colour);

                     red = -1;
                    blue = -1;
                    green = -1;
                }
                red = (int) (unsigned char) c;
                rgb_count++;

            } else if (rgb_count == 1) {
                green = (int) (unsigned char) c;
                rgb_count++;
            } else if (rgb_count == 2) {
                blue = (int) (unsigned char) c;
                rgb_count = 0;
            }
        }

    }
    infile.close();
}



The idea is to basically extract triplets of 3 bytes, then convert each to rgb respectively.

Problem is, when I display the image into the screen, the image isn't quite the same as it's supposed to be.

Where am I going wrong?

The original image:

enter image description here

Rendered Imageenter image description here image:

Upvotes: 0

Views: 1247

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

You read in a value for red, then increment j. Then you read in green, and increment j. Next you read blue, store the pixel value, and increment j.

So you're writing out your values spaced out every 3 rows.

Upvotes: 1

Related Questions