Jannik
Jannik

Reputation: 2429

Getting the SDL_Color of a single pixel in a SDL_Texture

I am having some problems finding a solution on how to retrieve a specific color of a pixel on a SDL_Texture... To be bit more specific: I am trying to calculate the average amount of color used in a given texture. Later on I want to devide for example the number of red pixels by the total amount of pixels. For this task I will need a method, which will get me each pixel color...

I tried to search for some functions, but unfortunately I wasnt able to figure it out.. I saw methods like SDL_RenderReadPixels and SDL_GetPixelFormatName, but none of those helped me out...

Do you have a solution for me?

Upvotes: 4

Views: 7855

Answers (1)

user2437378
user2437378

Reputation: 121

To access an SDL_Texture's pixels, you must create a blank texture using SDL_CreateTexture() and pass in SDL_TEXTUREACCESS_STREAMING for the access parameter, then copy the pixels of a surface into it. Once that's done, you can use the SDL_LockTexture() function to retrieve a pointer to the pixel data which can then be accessed and modified. To save your changes, you'd call SDL_UnlockTexture(). Try something like this:

SDL_Texture *t;

int main()
{
    // Init SDL 

    SDL_Surface * img = IMG_Load("path/to/file");
    SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, img->w, img->h);

    void * pixels;

    SDL_LockTexture(t, &img->clip_rect, &pixels, img->pitch);

    memcpy(pixels, img->pixels, img->w * img->h);

    Uint32 * upixels = (Uint32 *) pixels;

    // get or modify pixels

    SDL_UnlockTexture(t);

    return 0;
}

Uint32 get_pixel_at(Uint32 * pixels, int x, int y, int w)
{
    return pixels[y * w + x];
}

You can get the colors from a pixel like this:

Uint32 pixel = get_pixel_at(pixels, x, y, img->w);
Uint8 * colors = (Uint8 *) pixel;

// colors[0] is red, 1 is green, 2 is blue, 3 is alpha (assuming you've set the blend mode on the texture to SDL_BLENDMODE_BLEND

If you want more information, then check out these SDL 2.0 tutorials: http://lazyfoo.net/tutorials/SDL/index.php. Tutorial 40 deals specifically with this problem.

Let me know if you have any questions or something is unclear.

Good luck!

Upvotes: 6

Related Questions