Search code examples
c++sfml

How to put image pixel data into an array in code?


I want to integrate the icon pixel data into the code of my C++ program. I'm using the SFML library. The window method to set the icon looks like this:

void setIcon(unsigned int width, unsigned int height, const Uint8 *pixels)

Of course, SFML provides methods to read image files and get to the pixels. However, I don't want to read an image file; instead I would like to have the image pixel data in code, to be compiled into the executable. Something like:

sf::Uint8 pixels[] = { <image pixel data> };

How can I do that (if at all possible)?


Solution

  • Expanding on Eljay's comment:

    running xxd -i icon.png creates a file icon.h with the following content:

    unsigned char icon_png[] = { <image file data> };
    unsigned int icon_png_len = 264;
    

    Note that icon_png does not contain the pixel data, but the whole file (thus, including the file header). With SFML, this is the code to get to the pixel data:

    sf::Image icon;
    icon.loadFromMemory(icon_png, icon_png_len);
    window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());