Jump to content
  • Advertisement
Sign in to follow this  
c4c0d3m0n

Convert SDL_Surface to greyscale

This topic is 3694 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

// Load an image into a surface
SDL_Surface* loadImage( std::string filename, int flags )
{
    SDL_Surface* loaded_img = SDL_LoadBMP( filename.c_str() );
    SDL_Surface* optimized_img = NULL;

    if( loaded_img != NULL ) {
        optimized_img = SDL_DisplayFormat( loaded_img );
        SDL_FreeSurface( loaded_img );

        if( ( optimized_img != NULL ) && ( flags & GFX_IMG_COLORKEY ) )
          SDL_SetColorKey( optimized_img, SDL_SRCCOLORKEY, SDL_MapRGB( optimized_img->format, 0, 0xFF, 0xFF ) );
    }

    return optimized_img;
}
const int GFX_IMG_COLORKEY = 1;
const int GFX_IMG_GREYTONE = 2;
I would like to know how to manipulate my so that it becomes grayscale. I'm guessing this should be done after colorkeying, since otherwise I'd mess up the colors and the colorkey would fail. I have no clue how to do effects like this though. I'm planning on adding other effects later (ie inverted). Please help me by explaining how to convert a surface to grayscale. Should I do it pixel for pixel? I'm also not very good at color-theory, I can't do magix with color codes yet.

Share this post


Link to post
Share on other sites
Advertisement
The simplest way to convert to greyscale is to set all components of a pixel to the average of the RGB values.


// For each pixel in the surface
Uint8 avg = (r + g + b) / 3;
r = avg;
b = avg;
g = avg;

Share this post


Link to post
Share on other sites
I see, this per-pixel approach should work, although it's probably not very efficient. I tried using SDL_SetPalette() without any luck. I also played with the SDL_Surface*->format->Xmask's, also with no luck. I'll implement that average algorithm tonight, thanks for the reply.

Share this post


Link to post
Share on other sites
Thanks, that really helped me! I played around with those magic values a little, to get an effect that suits better my needs. Thanks again!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!