Can't save image to file properly with cimg library

Tneuktippa picture Tneuktippa · Apr 23, 2012 · Viewed 9.1k times · Source

Here is the entirety of my code:

#include "CImg.h"
#include <iostream>

using namespace cimg_library;
int main() {

CImg<float> image(100,100,1,3,0);
const float color[] = {1.0,1.0,0.0};
image.draw_point(50,50,color);
image.save("file.bmp");
CImgDisplay local(image, "Hah");
while (true) {
    local.wait();
    }   

}

This successfully displays what I expect in a window, namely, a completely black square with a white pixel at 50,50. However, file.bmp is simply a black square, without that pixel (and saving a cimg Image that has been modified with repeated calls to draw_point in a larger program that does something useful also fails). What's going on here?

Answer

Robᵩ picture Robᵩ · Apr 23, 2012

The problem is that you create CImgDisplay with normalization enabled. Thus, your pixel of {1,1,0} is normalized to {255,255,0} and is visible on your screen.

CImg.save does not perform normalization, so the the pixel is saved to disk as a very dark pixel.

You can fix the problem by changing your white pixel color:

const float color[] = {255.,255.,255.};

And, optionally, by disabling normalization:

CImgDisplay local(image, "Hah", 0);

In the alternative, you could normalize the original image before saving or displaying it:

image.draw_point(50,50,color);
image.normalize(0, 255);
image.save("file.bmp");

References: