SDL Gettin Pixel Color

Started by
3 comments, last by rip-off 15 years, 12 months ago
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 ) ;
}




Advertisement
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);
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.
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 :)
See here.

This topic is closed to new replies.

Advertisement