#include #include #include #include using namespace std; const int XDIM{1000}; const int YDIM{400}; using ColorT = unsigned char; struct PixelT { ColorT color[3]; }; using ImageT = vector >; void WriteImage(string baseFileName, const ImageT & image); int main() { vector> image(XDIM,vector(YDIM)); for(int i = 0; i < XDIM; ++i) { for(int j = 0; j < YDIM; ++j) { for(int k =0; k < 3; ++k) { image[i][j].color[k] = rand()%255; } } } WriteImage("foo", image); return 0; } void WriteImage(string baseFileName, const ImageT & image){ string pngName {baseFileName + ".ppm"}; // open a file for writing int flags = O_CREAT | O_WRONLY | O_TRUNC; int mode {S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR}; int fd {open(pngName.c_str(), flags, mode)}; if (-1 == fd) { perror("Error Open:"); } string tmp; tmp = "P6\n"; // write the PBM header // the magic number P6 (in ascii) followed by a newline write(fd, tmp.c_str(), sizeof(char) * tmp.size()); // width space height newline in ascii tmp = to_string(image.size()) + " " + to_string(image[0].size()) + "\n"; write(fd, tmp.c_str(), sizeof(char) * tmp.size()); // the maximum value (255) newline in ascii tmp = "255\n"; write(fd, tmp.c_str(), sizeof(char) * tmp.size()); // write the rgb values row by row in binary format for(int i = 0; i < image.size(); ++i) { for(int j = 0; j < image[0].size(); ++j) { write(fd, image[i][j].color, sizeof(ColorT) * 3); } } // close the file close(fd); // run ppmtogif or ppmtojpeg string jpegName{baseFileName + ".jpeg"}; string cmd { "ppmtojpeg < " + pngName + " > " + jpegName}; system(cmd.c_str()); unlink(pngName.c_str()); }