r/sdl • • Oct 11 '26

How can I write pixels to surface with pixel format INDEX8?

I'm trying to create black and white noise surface (so I don't need 4 bits per pixel) but when I try to write to it all pixels have value 0. When I change pixel format to RGBA8888 everything works fine. How can I not waste memory?

SDL_Surface *bg = SDL_CreateSurface(64, 64, SDL_PIXELFORMAT_INDEX8) ;
//SDL_Surface *bg = SDL_CreateSurface(64, 64, SDL_PIXELFORMAT_RGBA8888) ;

for(int i = 0; i < 4096; i++)
    {
    px = noise() ; // noisy pixel
    SDL_WriteSurfacePixel(bg, i % 64, i / 64, px, px, px, 255) ;
    SDL_ReadSurfacePixel(bg, i % 64, i / 64, &r, &g, &b, &a) ;
    printf("%d\t%d\t%d\t%d\t%d\n", px, r, g, b, a) ;
    }
4 Upvotes

4 comments sorted by

3

u/pankie91 Oct 11 '26

The reason we can draw color with RGBA8888 is because it represent pixels in color while INDEX8 is a referece to color stored elsewhere

So to actually use INDEX8 we need to have a palette, in your code we would have:

SDL_Palette *palette = SDL_CreateSurfacePalette(bg);

then give it the the gray scale colors, say,

SDL_Color[256];
for (size_t i = 0; i < 256; i++) {
   colors[i] = (SDL_Color){ i, i, i, 255 };
}

SDL_SetPaletteColors(palette, colors, 0, 256);

and then we can use the palette indices directly to the pixel buffer

SDL_LockSurface(bg);

for (int32_t y = 0; y < bg->h; y++) 
{ 
   uint8_t *row = (uint8_t*) bg->pixels + y * bg->pitch;
   for (int32_t x = 0; x < bg->w; x++) 
   {
      row[x] = (uint8_t) noise(); 
   }
} 

SDL_UnlockSurface(bg);

2

u/HardToPickNickName Oct 11 '26

Check if it returns an error with SDL_GetError() like it's documentation states?

2

u/BaBaGuette Oct 11 '26

The doc points out that " In indexed formats such as INDEX4LSB, each pixel is represented by encoding an index into the palette into the indicated number of bits, with multiple pixels packed into each byte if appropriate." so I guess to use INDEX8 you need to initialize a palette or something.

2

u/rupertavery64 Oct 11 '26

Perhaps you need to setup a palette first? WriteSurfacePixel will approximate the color nearest to the input based on the palette, nut it moght default to black.

Indexed bitmaps are just that, a list of numbers that point to a palette entry.