Setting up SDL2 in macOS (Xcode or CMake)

Supported Image Formats in SDL2_image

What image formats can I load using the SDL2_image library?

Abstract art representing computer programming

The SDL2_image library supports loading various common image formats, including:

  • PNG (.png)
  • JPEG (.jpg, .jpeg)
  • BMP (.bmp)
  • GIF (.gif)
  • TGA (.tga)
  • TIFF (.tif, .tiff)
  • WebP (.webp)

To load an image, you can use the IMG_Load function:

#include <SDL.h>
#include <SDL_image.h>
#include <iostream>

SDL_Surface* loadImage(const char* path) {
  SDL_Surface* surface = IMG_Load(path);
  if (surface == nullptr) {
    std::cout << "Failed to load image:"
      << IMG_GetError();
  }
  return surface;
}

int main(int argc, char** argv) {
  return 0;
}

Make sure to initialize the SDL2_image library before loading images:

if (IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG) == 0) {
  std::cout << "Failed to init SDL2_image:\n"
    << IMG_GetError();
  // handle error
}

The IMG_Init function takes a bitwise OR of the desired image format flags. In this example, we initialize support for PNG and JPEG images.

Remember to free the loaded surface when you're done using it:

SDL_FreeSurface(surface);

By using SDL2_image, you can easily load and work with a variety of image formats in your SDL2 projects.

This Question is from the Lesson:

Setting up SDL2 in macOS (Xcode or CMake)

This step-by-step guide shows you how to set up SDL2 in an Xcode or CMake project on macOS

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Setting up SDL2 in macOS (Xcode or CMake)

This step-by-step guide shows you how to set up SDL2 in an Xcode or CMake project on macOS

3D art representing computer programming
Part of the course:

Building Minesweeper with C++ and SDL2

Apply what we learned to build an interactive, portfolio-ready capstone project using C++ and the SDL2 library

Free, unlimited access

This course includes:

  • 37 Lessons
  • 100+ Code Samples
  • 92% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved