37 #include "ompl/util/PPM.h" 38 #include "ompl/util/Exception.h" 40 #include <boost/lexical_cast.hpp> 42 ompl::PPM::PPM() : width_(0), height_(0)
48 FILE *fp = fopen(filename,
"r");
50 throw Exception(
"Unable to load '" + std::string(filename) +
"'");
53 AutoClose(FILE *f) : f_(f) { }
54 ~AutoClose() { fclose(f_); }
60 if (fscanf(fp,
"%c", &p6[0]) != 1 || fscanf(fp,
"%c", &p6[1]) != 1 || p6[0] !=
'P' || p6[1] !=
'6')
61 throw Exception(
"Invalid format for file '" + std::string(filename) +
62 "'. PPM is expected to start with the characters 'P6'.");
64 while ((
char)nc !=
'#' && ((
char)nc >
'9' || (
char)nc <
'0')) nc = fgetc(fp);
66 while ((
char)nc !=
'\n') nc = fgetc(fp);
69 if (fscanf(fp,
"%d", &width_) != 1 || fscanf(fp,
"%d", &height_) != 1)
70 throw Exception(
"Unable to parse width and height for '" + std::string(filename) +
"'");
71 if (width_ <= 0 || height_ <= 0)
72 throw Exception(
"Invalid image dimensions for '" + std::string(filename) +
"'");
73 if (fscanf(fp,
"%d", &nc) != 1 || nc != 255 )
74 throw Exception(
"Invalid RGB component for '" + std::string(filename) +
"'");
76 nc = width_ * height_ * 3;
77 pixels_.resize(width_ * height_);
78 if ((
int)fread(&pixels_[0],
sizeof(
unsigned char), nc, fp) != nc)
79 throw Exception(
"Unable to load image data from '" + std::string(filename) +
"'");
84 if (pixels_.size() != width_ * height_)
85 throw Exception(
"Number of pixels is " + boost::lexical_cast<std::string>(pixels_.size()) +
86 " but the set width and height require " +
87 boost::lexical_cast<std::string>(width_ * height_) +
" pixels.");
89 fp = fopen(filename,
"wb");
91 throw Exception(
"Unable to open '" + std::string(filename) +
"' for writing");
93 fprintf(fp,
"%d %d\n", width_, height_);
94 fprintf(fp,
"%d\n", 255);
95 fwrite(&pixels_[0], 3 * width_, height_, fp);
void saveFile(const char *filename)
Save image data to a .ppm file. Throw an exception in case of an error.
void loadFile(const char *filename)
Load a .ppm file. Throw an exception in case of an error.
The exception type for ompl.