# SDL Gettin Pixel Color

## Recommended Posts

absolute    122
I am trying to get pixel color at a certain location. I have my function which returns the rgb of the pixel using SDL_Color. I want to check if this is actually working so after the color is returned I want to check the rgb values, by looking at color.r, color.b, color.g. Whenever I check them though, there is nothing stored in color.r, color.b, color.g. Shouldn't there be a number between 0-255 stored in each one? Code is below, thanks.

SDL_Color colour;
colour = GetPixel(background, 100, 100);
cout << colour.r << colour.g << colour.b;
//
//

SDL_Color GetPixel ( SDL_Surface* pSurface , int x , int y )
{
SDL_Color color ;
Uint32 col = 0 ;

//determine position
char* pPosition = ( char* ) pSurface->pixels ;

//offset by y
pPosition += ( pSurface->pitch * y ) ;

//offset by x
pPosition += ( pSurface->format->BytesPerPixel * x ) ;

//copy pixel data
memcpy ( &col , pPosition , pSurface->format->BytesPerPixel ) ;

//convert color
SDL_GetRGB ( col , pSurface->format , &color.r , &color.g , &color.b ) ;

return ( color ) ;
}



##### Share on other sites
Gage64    1235
What do you mean 'nothing'? obviously it contains some values, do you mean that they are not what you expect?

Also, I think the r, g, b are chars, so they are printed as such, which might make you think that their values are invalid. Try this instead:

cout << int(colour.r) << " " << int(colour.g) << " " << int(colour.b);

##### Share on other sites
MJP    19786
Typically you need to lock a surface with SDL_LockSurface before you can directly access a pixel. The only exception is if SDL_MUSTLOCK(surface) evaluates to 0. Make sure you unlock the surface when you're done.

##### Share on other sites
absolute    122
Thanks Gage64, putting in int(colour.g) worked. Before it showed nothing, meaning as if colour.g = " "; , just a space.

Also MJP , I have locksurface, but I just didn't include it in the code I posted. Thanks though :)

rip-off    10979
See here.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account