c++imagefreeimagestb-image

freeimage write to pixels


I am trying to write some vertices in a file using freeimage (but I am open to solutions with stb_image also).

I am trying to use the code from the Computer Graphics : Principles and Practice 3rd ed, chapter 3 , listing 3.6.

I am not sure how to handle the freeimage library.

Even though I set a red background color, I receive black.

Also, even though I am writing to file using setpixelcolor , I still receive a black window. The vertices should appear as green dots.

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <FreeImage.h>


typedef struct Point
{
    float x, y, z;
}Point;

int main() 
{
    int width = 400;
    int height = 300; 
    int bpp = 24; 

    FreeImage_Initialise();
    FIBITMAP *img = FreeImage_Allocate(width, height, bpp);
    RGBQUAD color;

    if (!img)
        exit(1);

    // build a table of vertices
    int nbOfPoints = 8;
    int nbOfEdges = 12;
    float vertices[nbOfPoints][3] = 
    {
        {-0.5, -0.5, 2.5},
        {-0.5, 0.5, 2.5},
        {0.5, 0.5, 2.5},
        {0.5, -0.5, 2.5},
        {-0.5, -0.5, 3.5},
        {-0.5, 0.5, 3.5},
        {0.5, 0.5, 3.5},
        {0.5, -0.5, 3.5}
    };

    // build a table of edges
    int edges[nbOfEdges][2] = 
    {
        {0, 1},
        {1, 2},
        {2, 3},
        {3, 0},
        {0, 4},
        {1, 5},
        {2, 6},
        {3, 7},
        {4, 5},
        {5, 6},
        {6, 7},
        {7, 4}
    };

    float xmin = -0.5;
    float xmax = 0.5;
    float ymin = -0.5;
    float ymax = 0.5;

    Point *pictureVertices = new Point[nbOfPoints * width * height];

    float scale = 100;

    BYTE *pixelData = NULL;

    RGBQUAD backg_color;// = new RGBQUAD(Color.Red);
    backg_color.rgbRed = 1.0;
    backg_color.rgbGreen = 0;
    backg_color.rgbBlue = 0;
    FreeImage_SetBackgroundColor(img, &backg_color);
    for (int j = height-1; j >= 0; --j)
    {
        for (int i = 0; i < width; ++i)
        {
            for (int p = 0; p < nbOfPoints; ++p)
            {
                float x = vertices[p][0];
                float y = vertices[p][1];
                float z = vertices[p][2];

                float xprime = x / z;
                float yprime = y / z;

                pictureVertices[p].x = scale * (1.0 - (xprime - xmin) / (xmax - xmin));
                pictureVertices[p].y = scale * (yprime - ymin) / (ymax - ymin);

                color.rgbRed = 0;
                color.rgbGreen = 1.0;
                color.rgbBlue = 0;
                FreeImage_SetPixelColor(img, pictureVertices[p].x, pictureVertices[p].y, &color);
                //FreeImage_SetPixelIndex(img,  (int)pictureVertices[i].x,  (int)pictureVertices[i].y, pixelData);
            }
        }
    }
    FreeImage_Save(FIF_PNG, img, "test.png", 0);
    FreeImage_DeInitialise();


    std::cout << "\n";

    return 0;
}

Solution

  • You should use the range 0..255, and not 0..1 :)