From 69ec57307c1ae55b862bae87eb9613ba9bd5e475 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Jos=C3=A9=20Fonseca?= Date: Tue, 6 Sep 2011 09:19:57 +0100 Subject: [PATCH] Optimize Image::writePNM. --- image_pnm.cpp | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/image_pnm.cpp b/image_pnm.cpp index 44ae624..82c2dde 100644 --- a/image_pnm.cpp +++ b/image_pnm.cpp @@ -26,7 +26,7 @@ #include -#include +#include #include "image.hpp" @@ -55,15 +55,29 @@ Image::writePNM(std::ostream &os, const char *comment) const { os.write((const char *)row, width*channels); } } else { - unsigned char pixel[3] = {0, 0, 0}; - for (row = start(); row != end(); row += stride()) { - for (unsigned x = 0; x < width; ++x) { - for (unsigned channel = 0; channel < channels; ++channel) { - pixel[channel] = row[x*channels + channel]; + unsigned char *pixels = new unsigned char[width*3]; + if (channels == 4) { + for (row = start(); row != end(); row += stride()) { + for (unsigned x = 0; x < width; ++x) { + pixels[x*3 + 0] = row[x*4 + 0]; + pixels[x*3 + 1] = row[x*4 + 1]; + pixels[x*3 + 2] = row[x*4 + 2]; + } + os.write((const char *)pixels, width*3); + } + } else if (channels == 2) { + for (row = start(); row != end(); row += stride()) { + for (unsigned x = 0; x < width; ++x) { + pixels[x*3 + 0] = row[x*2 + 0]; + pixels[x*3 + 1] = row[x*2 + 1]; + pixels[x*3 + 2] = 0; } - os.write((const char *)pixel, sizeof pixel); + os.write((const char *)pixels, width*3); } + } else { + assert(0); } + delete [] pixels; } } -- 2.45.2