0
votes

I have 2x2 image

Shouldn't the pixels be arranged like this?

1 2 // each number is a pixel
3 4

I'm having trouble accessing a pixel with x and y because when x = 1 and y = 0 i get index 2 but prints the rgb values of pixel 4

so it's something like?

1 2 // each number is a pixel
4 3

Here's the code that I use

index = y + x * s->w;
c = s->format->palette->colors[index]; // c is an SDL_Color and s is an SDL_Surface*

I also use this for loop and still prints the same

for (Uint8 i = *(Uint8 *)s->pixels; i < s->w*s->h; i++) {
    c = s->format->palette->colors[i];
    printf("%u %u %u %u \n", i, c.r , c.g , c.b);
}

SDL_Surface struct definition from the SDL documentation

typedef struct SDL_Surface {
    Uint32 flags;                           /* Read-only */
    SDL_PixelFormat *format;                /* Read-only */
    int w, h;                               /* Read-only */
    Uint16 pitch;                           /* Read-only */
    void *pixels;                           /* Read-write */

    /* clipping information */
    SDL_Rect clip_rect;                     /* Read-only */

    /* Reference count -- used when freeing surface */
    int refcount;                           /* Read-mostly */

/* This structure also contains private fields not shown here */
} SDL_Surface;
1
I've edited the code - User9123
You should use pixels to access pixels, colors looks like a color table. - Jean-Baptiste Yunès
The documentation said, " So, to determine the color of a pixel in a 8-bit surface: we read the color index from surface->pixels and we use that index to read the SDL_Color structure from surface->format->palette->colors. " - User9123
Your quote is the answer. You should get the index from ->pixels, not compute it. - HolyBlackCat
'for (Uint8 i = *(Uint8 *)s->pixels; i < s->w * s->h; i++) { c = s->format->palette->colors[i]; printf("%u %u %u %u \n", i, c.r , c.g , c.b); }' prints the same - User9123

1 Answers

0
votes
Uint8 *pixel = (Uint8 *)s->pixels,*index;
index = &pixel[y + x * s->pitch];
c = s->format->palette->colors[*index];

Got it doing using @holyblackcat's suggestion.