[ACCEPTED]-How to load JPG/PNG Textures in an SDL/OpenGL App under OSX-jpeg
Have a look at the SDL_image library. It offers functions 4 like IMG_LoadPNG
that load your picture "as an" SDL_Surface.
Since 3 you already work with SDL this should fit 2 quite well in your program.
Sample taken 1 from the SDL_image documentation:
// Load sample.png into image
SDL_Surface* image = IMG_Load("sample.png");
if (image == nullptr) {
std::cout << "IMG_Load: " << IMG_GetError() << "\n";
}
SDL 2 SDL_image minimal runnable example
main.c
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
int main(void) {
SDL_Event event;
SDL_Renderer *renderer = NULL;
SDL_Texture *texture = NULL;
SDL_Window *window = NULL;
SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO);
SDL_CreateWindowAndRenderer(
500, 500,
0, &window, &renderer
);
IMG_Init(IMG_INIT_PNG);
texture = IMG_LoadTexture(renderer, "flower.png");
while (1) {
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
if (SDL_PollEvent(&event) && event.type == SDL_QUIT)
break;
}
SDL_DestroyTexture(texture);
IMG_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
Compile and run:
sudo apt-get install libsdl2-dev libsdl2-image-dev
gcc -std=c99 -o main -Wall -Wextra -pedantic main.c -lSDL2 -lSDL2_image
./main
Outcome:
Tested on 2 Ubuntu 16.04, GCC 6.4.0, SDL 2.0.4, SDL 1 Image 2.0.1.
Take a look at freeimage. It supports all major formats 3 and is easily built with macports. Nice 2 to work with as well. Auto-detects image 1 format etc.
FREE_IMAGE_FORMAT format = FreeImage_GetFileType(filename.c_str(), 0);
FIBITMAP *bitmap = FreeImage_Load(format, filename.c_str());
if (!bitmap)
{
LOG_ERROR("Unable to load texture: " + filename);
return false;
}
mlWidth = FreeImage_GetWidth(bitmap);
mlHeight = FreeImage_GetHeight(bitmap);
glGenTextures(1, &mpTextures[0]);
glBindTexture(GL_TEXTURE_2D, mpTextures[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mlWidth, mlHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE,
(GLvoid*)FreeImage_GetBits(bitmap));
FreeImage_Unload(bitmap);
If you're on Mac OS anyway, why not just 3 use CGImageSource to do the loading? OS X natively supports 2 loading many file formats including PNG 1 and JPEG.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.