How to get the color of a specific pixel from SDL_Surface?

折月煮酒 提交于 2021-01-05 07:25:24

问题


I'm trying to get the RGB/RGBA color of pixels from a SDL_Surface. I've found this code on the internet but it returns strange numbers (67372036 for a pixel that is 0 red, 0 green, 255 blue)

Uint32 get_pixel32(SDL_Surface *surface, int x, int y)
{
    Uint32 *pixels = (Uint32 *)surface->pixels;
    return pixels[(y * surface->w) + x];
}

This it the code I've been using:

Uint32 data = get_pixel32(gSurface, 0, 0);
printf("%i", data);

I'm not sure if my pixels have a 32bit format but other pictures didn't work as well.


回答1:


Found this code and it's working fine.

Uint32 getpixel(SDL_Surface *surface, int x, int y)
{
    int bpp = surface->format->BytesPerPixel;
    /* Here p is the address to the pixel we want to retrieve */
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp;

switch (bpp)
{
    case 1:
        return *p;
        break;

    case 2:
        return *(Uint16 *)p;
        break;

    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;
            break;

        case 4:
            return *(Uint32 *)p;
            break;

        default:
            return 0;       /* shouldn't happen, but avoids warnings */
      }
}



SDL_Color rgb;
Uint32 data = getpixel(gSurface, 200, 200);
SDL_GetRGB(data, gSurface->format, &rgb.r, &rgb.g, &rgb.b);



回答2:


It depends on the color format of the surface, or SDL_PixelFormat. You can follow what is presented on that page, or just use SDL_GetRGB.



来源:https://stackoverflow.com/questions/53033971/how-to-get-the-color-of-a-specific-pixel-from-sdl-surface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!