Setting up stb_image 2.30 in Visual Studio 2022 using CMake
- Install stb_image using this guide: How to install stb_image
- Install VS 2022 and CMake using this guide: Installation of Visual Studio 2022 Community with CMake support
- Run Visual Studio
- Click on the "Create a new project" button:
- Click on the "CMake Project" and click on the "Next" button:
- Type a project name, set a project location, check the "Place solution and project in the same directory" checkbox, and click on the "Create" button:
- Wait a few seconds for configuration
- Run the project by click on the empty green triangle (or Ctrl+F5):
- The program prints "Hello CMake" to the console:
- Download some PNG image file, for example, this free crate: https://opengameart.org/content/crate-5 - click on the crate.7z
- Unzip "crate.7z" somewhere and copy the "clear_01.png" file
- Open your "hello-stb-image" project in the file explorer, create the "assets/sprites" folder, and paste the "clear_01.png" in the folder like this:
- Double click on the "CMakeLists.txt" file:
- Copy the following code to the "CMakeLists.txt" but change the stb_image location on yours:
| target_include_directories(hello-stb-image PRIVATE E:/libs/stb_image-2.30/include) |
| |
| |
| add_custom_command(TARGET hello-stb-image POST_BUILD |
| COMMAND ${CMAKE_COMMAND} -E copy_directory |
| ${CMAKE_SOURCE_DIR}/assets $<TARGET_FILE_DIR:hello-stb-image>/assets) |
Double click on the "hello-stb-image.cpp" file:
Copy the following content to the "hello-stb-image.cpp" file:
| #include <iostream> |
| |
| #define STB_IMAGE_IMPLEMENTATION |
| #include <stb_image.h> |
| |
| int main() |
| { |
| const char* path = "./assets/sprites/clear_01.png"; |
| int w_image, h_image, cnt; |
| unsigned char* data = stbi_load(path, &w_image, &h_image, &cnt, 0); |
| if (data == NULL) |
| { |
| std::cout << "Failed to load the image: " << path << std::endl; |
| return 1; |
| } |
| std::cout << "w = " << w_image << std::endl; |
| std::cout << "h = " << h_image << std::endl; |
| return 0; |
| } |
Press Ctrl+F5 to run the application
You see the result in the console - width and height of the loaded image:
Next guide: Drawing a crate on the screen using OpenGL and SDL3