Home > Net >  How do I draw and write to a ppm file?
How do I draw and write to a ppm file?

Time:09-17

I want to draw lines/shapes and output to a ppm file, but I don't know how to even draw individual pixels. I know how to output to a file and that there's a nested for loop method for drawing pixels (found this code online), but I was wondering if there's an easier way to handle it.

for (auto j = 0u; j < dimy;   j)
    for (auto i = 0u; i < dimx;   i)
        ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);

I'm taking a class that uses C , but it's my first time working with the language, so please make your answers somewhat simple to understand (I've coded in Java before if that helps). Also, please don't list any features past C 11. Thank you in advance! :)

CodePudding user response:

I suggest you have a look at the ppm format. https://en.wikipedia.org/wiki/Netpbm#File_formats

All you're doing is constructing a character string like this:

1 0 0   0 1 0   0 0 1
1 1 0   1 1 1   0 0 0

So, you could for example use nested arrays and a nested loop to traverse it.

This code would generate an std::ostringstream whose string represents the post-header part of a 2x4 ppm file that is pure black everywhere except on the 2nd line, 3rd column pixel, where it is red.

#include <iostream>
#include <sstream>

[...]

const int length = 2;
const int width = 4;

uint8_t table[length][width][3]{};

std::ostringstream oss;

table[1][2][0] = 255;

for (int i = 0; i < length; i  ) {
    for (int j = 0; j < width; j  ) {
        for (int k = 0; k < 3; k  ) {
            oss << (int)table[i][j][k] << " ";
        }
        oss << "\n";
    }
    oss << "\n";
}
  • Related