save png from the results of glReadPixels

977 views Asked by At

From previous questions 1 and 2, I have the following codes:

How to capture screen:

int width = glutGet(GLUT_WINDOW_WIDTH);
int height = glutGet(GLUT_WINDOW_HEIGHT);

std::vector< unsigned char > rgbdata(4*width*height);
glReadPixels(0, 0, width, height,GL_RGBA,GL_UNSIGNED_BYTE, &rgbdata[0]);

int save_result = SOIL_save_image
    (
        filename,
        SOIL_SAVE_TYPE_PNG,
        width, height, 4,
        rgbdata.data()
    );

and how to store in PNG:

#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/gil_all.hpp>
#include <boost/gil/extension/io/png_dynamic_io.hpp>
using namespace boost::gil;
int main()
{
    rgb8_image_t img(512, 512);
    rgb8_pixel_t red(255, 0, 0);
    fill_pixels(view(img), red);
    png_write_view("redsquare.png", const_view(img));
}

I want to save the captured screen into a png file. Now, the question is how to cascade these codes to each other? Are these arrays convertible to each other?

1

There are 1 answers

0
Malcolm McLean On

Who knows? It;s best to pass images around as raw pointers allocated with C malloc, largely because people create aliases for what is essentially the same data type, and that gets templates into a mess.

Choose rgb or rgba as your internal format. Then write glue code to convert to the format the third library party wants. In this case, Boost is taking an rgb8_image_t, which Boost itself creates. You don't want that symbol polluting your namespace anywhere else except at the exact point you rely on bool gil to save an image. So write a wrapper and then fiddle with Boost until the format comes right.

If you use the Baby X file saving routines these problems just disappear. The routines take unsigned char buffers and don't try to export data types for images.

https://github.com/MalcolmMcLean/babyxrc

(lodePNG isn't mine, it was written by Lode Vandevenne, so please obey the licence requirements. You can do what you want with the other formats as they were authored by me).