X-Git-Url: https://git.cworth.org/git?a=blobdiff_plain;f=common%2Fimage_pnm.cpp;h=f9cd05d1fbc7593dafcb6e5bf77d48beb7505a1d;hb=1242ab5cbdc409e2fc2d787edc28c6ac2a8439d1;hp=5397a1a604d78d7c4afc45ad38ef500f2688a1ce;hpb=ae2b4d32ed56e3ac193cc7205aeb58082c448ce8;p=apitrace diff --git a/common/image_pnm.cpp b/common/image_pnm.cpp index 5397a1a..f9cd05d 100644 --- a/common/image_pnm.cpp +++ b/common/image_pnm.cpp @@ -28,11 +28,12 @@ #include #include #include +#include #include "image.hpp" -namespace Image { +namespace image { /** * http://en.wikipedia.org/wiki/Netpbm_format @@ -108,5 +109,55 @@ Image::writePNM(std::ostream &os, const char *comment) const { } } +const char * +readPNMHeader(const char *buffer, size_t bufferSize, unsigned *channels, unsigned *width, unsigned *height) +{ + *channels = 0; + *width = 0; + *height = 0; -} /* namespace Image */ + const char *currentBuffer = buffer; + const char *nextBuffer; + + // parse number of channels + int scannedChannels = sscanf(currentBuffer, "P%d\n", channels); + if (scannedChannels != 1) { // validate scanning of channels + // invalid channel line + return buffer; + } + // convert channel token to number of channels + *channels = (*channels == 5) ? 1 : 3; + + // advance past channel line + nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; + bufferSize -= nextBuffer - currentBuffer; + currentBuffer = nextBuffer; + + // skip over optional comment + if (*currentBuffer == '#') { + // advance past comment line + nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; + bufferSize -= nextBuffer - currentBuffer; + currentBuffer = nextBuffer; + } + + // parse dimensions of image + int scannedDimensions = sscanf(currentBuffer, "%d %d\n", width, height); + if (scannedDimensions != 2) { // validate scanning of dimensions + // invalid dimension line + return buffer; + } + + // advance past dimension line + nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; + bufferSize -= nextBuffer - currentBuffer; + currentBuffer = nextBuffer; + + // skip over "255\n" at end of header + nextBuffer = (const char *) memchr((const void *) currentBuffer, '\n', bufferSize) + 1; + + // return start of image data + return nextBuffer; +} + +} /* namespace image */