'C++ SFML Failed to load image, reason: Unable to open file
I am trying to display an empty window in C++ using the SFML library. However, it gives me an error when I am loading an image with loadFromFile.
Failed to load image "enemy.png". Reason: Unable to open file
The image, "enemy.png" is in the source files directory (Using Visual Studio 2019), as well as the main.cpp file. I have downloaded the SFML x64-bit files and used dynamic linking through the project properties. I have tried to remove the load image part, and that successfully loads the window. But this isn't good because it won't work if I need to load a picture next time.
Here is the code:
#include <SFML/Graphics.hpp>
int main() {
float windowHeight = 400;
float windowWidth = 400;
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "Rougelike");
sf::Texture texture;
if (!texture.loadFromFile("enemy.png")) {
return 0;
}
sf::Sprite sprite;
sprite.setTexture(texture);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
window.clear();
window.draw(sprite);
window.display();
}
}
After running the code, this is what I get from the output:
Build started...
1>------ Build started: Project: Project1, Configuration: Debug x64 ------
1>main.cpp
1>D:\XXX\XXX\Project1\Project1\main.cpp(7,56): warning C4244: 'argument': conversion from 'float' to 'unsigned int', possible loss of data
1>D:\XXX\XXX\Project1\Project1\main.cpp(7,43): warning C4244: 'argument': conversion from 'float' to 'unsigned int', possible loss of data
1>Project1.vcxproj -> D:\XXX\XXX\Project1\x64\Debug\Project1.exe
1>Done building project "Project1.vcxproj".
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
And this is what I get from the command prompt:
Failed to load image "enemy.png". Reason: Unable to open file
D:\XXX\XXX\Project1\x64\Debug\Project1.exe (process 19768) exited with code 0.
Press any key to close this window . . .
Thanks.
Solution 1:[1]
I had the same problem. I placed the image in the root
of my project and it didn't work. Then I searched for the file in the explorer in windows and copied the complete path like C:\Users\myname\project\graphics\yourimage.png
, then it worked.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Avinash |