Question

I have been following the tutorials on SFML and tried to load a texture using the following code

sf::Texture texture;
if (!texture.loadFromFile("image.png"))
{
    return sf::Texture();
}

This fails to load the texture, the sprite is white which is not the colour of my sprite..

Was it helpful?

Solution

As taken directly from the graphics-sprite tutorial on the SFML website

"The loadFromFile function sometimes fails with no obvious reason. First, check the error message printed by SFML in the
standard output (check the console). If the message is unable to open file, make sure that the working directory (which is the
directory any file path will be interpreted relatively to) is what you think it is: when you run the application from the explorer, the
working directory is the executable folder, but when you launch your program from your IDE (Visual Studio, Code::Blocks, ...) the
working directory is sometimes set to the project directory instead. This can generally be changed easily in the project settings." 

Therefore ensure your image is firstly named correctly and secondendly make sure it is in the correct folder i.e. in your working directory.

Also if the texture fails to load instead of returning an empty sprite you could report an error to the console and then throw an exception. This way you will be told the sprite does not load correctly and the program will have to handle the exception otherwise it will be terminated. This way no sprite in the game should have a white texture unless intentional

Something like this:

sf::Texture texture;
if (!texture.loadFromFile("image.png"))
{
    throw std::runtime_error("Could not load image.png");
}

OTHER TIPS

Loading a PNG ? Make it 8bit. Other png formats can be loaded but are always displayed as white squares.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top