justinzane
justinzane

Reputation: 1987

How to convert any SDL_Surface to RGBA8888 format and back?

I want to convert any SDL_Surface my function receives to an RGBA8888 format surface, do stuff, and convert it back to its original format before return.

I'm working in C, by the way.

//------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
//------------------------------------------------
SDL_Surface* formattedSurf = SDL_ConvertSurfaceFormat(surf, 
                                                      SDL_PIXELFORMAT_RGBA8888, 
                                                      0);

yields: "Problem description: Symbol 'SDL_PIXELFORMAT_RGBA8888' could not be resolved" from Eclipse CDT and similar rsponses from gcc.

[Thu 13/09/26 14:40 PDT][pts/3][x86_64/linux-gnu/3.11.1-1-ARCH][5.0.2]
<justin@justin-14z:/tmp>
zsh/2 1821 % pkg-config --cflags --libs sdl
-D_GNU_SOURCE=1 -D_REENTRANT -I/usr/include/SDL -lSDL -lpthread 

Upvotes: 2

Views: 4524

Answers (2)

TPS
TPS

Reputation: 2137

Assuming the surface you have is called surface and is valid i.e. not NULL

// Store the current pixel format flag
Uint32 currFormat = surface->format->format;

// Convert the surface to a new one with RGBA8888 format
SDL_Surface* formattedSurf = SDL_ConvertSurfaceFormat(surf, 
                                                      SDL_PIXELFORMAT_RGBA8888, 
                                                      0);

if (formattedSurf != NULL) {

    // Free original surface
    SDL_FreeSurface(surface);

    ////////////////////////
    // DO YOUR STUFF HERE //
    ////////////////////////

    // Re-create original surface with original format
    surface = SDL_ConvertSurfaceFormat(formattedSurf, currFormat, NULL);

    // Free the formatted surface
    SDL_FreeSurface(formattedSurf);

}
else {

    /////////////////////////////////////
    // LOG A WARNING OR SOMETHING HERE //
    /////////////////////////////////////

}

Upvotes: 5

emartel
emartel

Reputation: 7773

I never had to use it, but it looks like SDL_ConvertSurface (link) would do what you need if you create a SDL_PixelFormat (link) that corresponds to your RGBA8888 format.

Upvotes: 1

Related Questions