Search code examples
c++sfml

How to load a sf::Image from an array of pixels in SFML?


I would like to load an image in sfml from a 2d array containing 3 values for each pixel (RGB). The array would look something like this:

{
 {{255, 255, 255}, {255, 255, 255}},
 {{255, 255, 255}, {255, 255, 255}}
}

The array above describes a 2x2 image which is white. How can I turn this into an Image in sfml (sf::Image)?


Solution

  • If you want to create an sf::Image object from a pixel array, then you are interested in the sf::Image::create() member function overload that takes a const Uint8 *:

    void sf::Image::create(unsigned int width, unsigned int height, const Uint8 * pixels);  
    

    As the name suggests, the last parameter, pixels, corresponds to the array of pixels you want to create the sf::Image from. Note that this pixel array is assumed to be in the RGBA format (this contrasts with the RGB format suggested in the code of the question). That is, the array must hold four Uint8s for each pixel – i.e., a Uint8 for each component: red, green, blue and alpha.


    As example, consider the following pixel array, pixels, made up of six pixels:

    const unsigned numPixels = 6;
    sf::Uint8 pixels[4 * numPixels] = {
        0,   0,   0,   255, // black
        255, 0,   0,   255, // red
        0,   255, 0,   255, // green
        0,   0,   255, 255, // blue
        255, 255, 255, 255, // white
        128, 128, 128, 255, // gray
    };
    

    Then, we can create an sf::Image object from the pixels array of pixels:

    sf::Image image;
    image.create(3, 2, pixels);
    

    The pixels of the sf::Image created above will correspond to these:

    3x2 image

    This is a 3x2-pixel image, However, flipping the image's width and height arguments passed to the sf::Image::create() as done in:

    sf::Image image;
    image.create(2, 3, pixels);
    

    This results in a 2x3-pixel image instead:

    3x3 image

    Note, however, that both sf::Image objects above are created from the same array of pixels, pixels, and they both are made up of six pixels – the pixels are just arranged differently because the images have different dimensions. Nevertheless, the pixels are the same: a black, a red, a green, a blue, a white and a gray pixel.