如何在 exe 文件夹中不包含纹理

How to not include texture in exe folder

本文关键字:包含 纹理 文件夹 exe      更新时间:2023-10-16

我正在为学校做一些sfml项目,老师只想要.exe程序。我正在使用Visual Studio 2017。在这个项目中,我正在使用.jpg文件中的纹理

sf::RenderWindow window(sf::VideoMode(640, 480, 32), "Kurs SFML ");
sf::Texture texture; 
texture.loadFromFile("wood.jpg");
sf::Sprite pic;
pic.setTexture(texture);
while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }
    window.clear();
    window.draw(pic);
    window.display(); 

这个文件(wood.jpg(需要与项目在同一个文件夹中才能显示这种纹理,否则它只显示黑屏。当我检查另一个文件夹中的.exe程序时,它还需要此文件在此文件夹中,否则.exe显示黑屏。但是我的老师只想要.exe没有任何文件夹的文件。那么是否可以做一些事情来不包括这个文件( wood.jpg (,而是在.exe中显示纹理?

可执行文件中嵌入纹理。

一个简单的解决方案是编写一个小工具,用于读取文件并写出一个C++源文件,其中包含包含原始字节的constexpr std::array。然后从链接到可执行文件的该变量(SFML 具有从内存加载资源的函数(加载纹理。

编写这样的工具不应超过 10-20 行代码。

对于特定于 SFML 的解决方案,您可以执行此操作。

sf::Image tmp;
tmp.loadFromFile("super.jpeg");
std::ofstream file;
file.open("textarray.cpp");
size_t psize = tmp.getSize().x * tmp.getSize().y * 4;
auto ptr = tmp.getPixelsPtr();
file << "sf::Uint8 imageArray[] = {" << (int)ptr[0];
for (size_t i = 1; i<psize; ++i)
    file << "," << (int)ptr[i];
file << "};";
file.close();

这将创建一个文件名 textarray.cpp其中包含看起来像 sf::Uint8 imageArray[] = {...};

然后你可以像这样在程序中加载它。

sf::Uint8 imageArray[] = {...};
sf::Image img;
img.create(80, 80, imageArray); // Replace 80, 80 with width and height of your image!!!
sf::Texture texture;
texture.loadFromImage(img);
sf::Sprite sprite;
sprite.setTexture(texture);

从这里开始,只需像往常一样绘制精灵即可。