0
votes

How can I read and write pixel data contained in a SDL_Surface in SDL2? (1)

I tried searching online for a solution to this but didn't find anything which suprised me. I remember it could be done in the SDL 1.2, but I can't find anything relevant to SDL 2.*

*(With the exception of manupulating textures, which isn't what I want to do. The results will be the same but I don't want to edit an object which resides in GPU memory.)

I have an SDL_Surface and I want to manipulate the pixels. The reason I want to do this is because I want to translate all black pixels into white pixels. (2)

I then load the surface into a texture object for rendering.

I wasn't able to find a solution to (2) so I tried a manual approach with (1).

1

1 Answers

2
votes

The SDL_Surface structure has a field named pixels which is an array containing every pixel from left to right, top to bottom, using some pixel format (given by the field format).

You can directly modify this pixel array if SDL_MUSTLOCK(surface) is false. Otherwise, you need to lock the surface beforehand and unlock it afterwards, using SDL_LockSurface (and SDL_UnlockSurface).

More information can be found in the SDL_Surface page. Taking the remark into consideration, the pixels field is read-only if the surface has been optimized for RLE acceleration. Otherwise, it should be fine to modify the pixels directly.