windows 如何在 C++ 可执行文件中包含图像作为资源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/549031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you include images as resources in a C++ executable?
提问by
Is it possible include images (jpegs) as resources in a win32 c++ executable? If so how?
是否可以在 win32 c++ 可执行文件中包含图像(jpegs)作为资源?如果是这样怎么办?
采纳答案by John Smith
Here's the MSDN documentation about resource files.
这是有关资源文件的 MSDN 文档。
http://msdn.microsoft.com/en-us/library/aa380599(VS.85).aspx
http://msdn.microsoft.com/en-us/library/aa380599(VS.85).aspx
回答by Rob
If it's Windows only then use a custom resource. If you want something cross-platform then do what I did for a recent project - create an app that will encode the JPEG as a char*
buffer in a header file and then include these headers in your main project. You will also need to store the size of the buffer as it will be sure to contain NULs.
如果它只是 Windows,则使用自定义资源。如果你想要跨平台的东西,那么做我最近为一个项目做的事情 - 创建一个应用程序,将 JPEG 编码为char*
头文件中的缓冲区,然后将这些头文件包含在你的主项目中。您还需要存储缓冲区的大小,因为它肯定会包含 NUL。
For example, I have an app that you can pass a load of files to be encoded and for each file you get a header file that looks something like this:
例如,我有一个应用程序,您可以传递大量要编码的文件,并且对于每个文件,您都会获得一个类似于以下内容的头文件:
#ifndef RESOURCE_SOMEFILE_JPG_HPP
#define RESOURCE_SOMEFILE_JPG_HPP
namespace resource {
const char* SOMEFILE_JPG[] =
{
...raw jpeg data...
};
const int SOMEFILE_JPG_LEN = 1234;
} // resource
#endif // RESOURCE_SOMEFILE_JPG_HPP
The app has to escape special non-printable chars in \x
format, but it's pretty simple. The app uses the boost::program_options
library so a list of files to encode can be stored in a config file. Each file gets its own header like similar to the above.
该应用程序必须在\x
格式上转义特殊的不可打印字符,但这非常简单。该应用程序使用该boost::program_options
库,因此可以将要编码的文件列表存储在配置文件中。每个文件都有自己的标题,类似于上面的。
However, be warned - this only works for small files as some compilers have a limit on the maximum size a static char buffer can be. I'm sure there are other ways to do this but this scheme works for me (a C++ web app that stores the HTML, CSS, JavaScript and image files in this way).
但是,请注意 - 这仅适用于小文件,因为某些编译器对静态字符缓冲区的最大大小有限制。我确信还有其他方法可以做到这一点,但这个方案对我有用(一个 C++ 网络应用程序,以这种方式存储 HTML、CSS、JavaScript 和图像文件)。