Hi All,
I’m faced with what must surely be a common problem - reading the color of a
pixel on an SDL surface. I’ve struggled with three methods (shown below)
gleamed from the SDL documentation and other sources on the web, but in all
cases the program GPF’s on the SDL_GetRGBA call.
The display surface i’m attempting to read doesn’t need locking (according to
SDL_MUSTLOCK) and has 4 bytes per pixel. I’m sure its just something in the way
i’m passing the first parameter to SDL_GetRGBA but its got me stumped.
Any advice on how to successfully read a pixel would be greatly appreciated.
Thanks in advance.-----------------------------------------------------------------------------
METHOD 1
Uint32 getpixel(SDL_Surface *surface, int x, int y) {
int bpp = surface->format->BytesPerPixel;
Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;
switch(bpp) {
case 1: return *p;
case 2: return *(Uint16 *)p;
case 3: if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
return p[0] << 16 | p[1] << 8 | p[2];
else
return p[0] | p[1] << 8 | p[2] << 16;
case 4: return *(Uint32 *)p;
default: return 0;
}
}
Uint32 c = getpixel(screen,x,y);
Uint8 R, G, B, A;
SDL_GetRGBA(c,screen->format,&R,&G,&B,&A);
METHOD 2
char* p = (char*)screen->pixels;
p += (screen->pitch * y);
p += (screen->format->BytesPerPixel * x);
Uint8 R, G, B, A;
SDL_GetRGBA((Uint32)(*p),screen->format,&R,&G,&B,&A);
METHOD 3
Uint16 getpixel(SDL_Surface *surface, int x, int y) {
Uint8 *p = (Uint8 )surface->pixels + y * surface->pitch
+ x * surface->format->BytesPerPixel;
return ((Uint16 *)p);
}
Uint16 c = getpixel(screen,x,y);
Uint8 R, G, B, A;
SDL_GetRGBA((Uint32)c,screen->format,&R,&G,&B,&A);