SFML community forums

Help => General => Topic started by: Cmdu76 on August 22, 2016, 08:10:29 am

Title: Load From Memory
Post by: Cmdu76 on August 22, 2016, 08:10:29 am
Hi !

Can someone explain to me how to load a texture from memory ?

std::string data = ...;
sf::Texture texture;
texture.loadFromMemory(data.data(), data.size());
 

What to I need to put in data ?
Title: Re: Load From Memory
Post by: Jesper Juhl on August 22, 2016, 08:32:28 am
First of all you should probably use a
std::vector<uint8_t>
rather than a
std::string
for your data.

Second, you need to put your image data in there - a PNG image for example.
Title: Re: Load From Memory
Post by: Cmdu76 on August 22, 2016, 08:58:43 am
Thanks !

And how do I convert my image .png into the vector ?
Title: Re: Load From Memory
Post by: Cmdu76 on August 22, 2016, 09:37:43 am
Someone on IRC finally helped me !

(Sorry I don't remember who exactly, there were a lot of people trying to help)

I used this :

#include <fstream>
#include <assert.h>
 
int main(int argc, char* argv[]) {
    assert(argc == 2);
    char* fn = argv[1];
    std::ifstream f(fn,std::ios::binary);
    FILE* out = fopen("out.cpp", "w");
    fprintf(out,"char a[] = {\n");
    unsigned long n = 0;
    while (!f.eof())
    {
        char c;
        f.read(&c, 1);
        unsigned char uc = c;
        fprintf(out,"0x%.2X,", (int)uc);
        ++n;
        if (n % 10 == 0) fprintf(out,"\n");
    }
    f.close();
    fprintf(out,"};\n");
    fclose(out);
}

and in my code :

texture.loadFromMemory(&a, sizeof(a));