Search code examples
cpixelsdl-2

Pixel manipulation with SDL surface?


I'm trying to play around with image manipulation in C and I want to be able to read and write pixels on an SDL Surface. (I'm loading a bmp to a surface to get the pixel data) I'm having some trouble figuring out how to properly use the following functions.

SDL_CreateRGBSurfaceFrom();
SDL_GetRGB();
SDL_MapRGB();

I have only found examples of these in c++ and I'm having a hard time implementing it in C because I don't fully understand how they work.

so my questions are:

  1. how do you properly retrieve pixel data using GetRGB? + How is the pixel addressed with x, y cordinates?

  2. What kind of array would I use to store the pixel data?

  3. How do you use SDL_CreateRGBSurfaceFrom() to draw the new pixel data back to a surface?

Also I want to access the pixels individually in a nested for loop for y and x like so.

for(int y = 0; y < h; y++)
{
    for (int x = 0; x < w; x++)
    {
     // get/put the pixel data
    }
} 

Solution

  • First have a look at SDL_Surface.

    The parts you're interested in:

    What else you should know:

    On position x, y (which must be greater or equal to 0 and less than w, h) the surface contains a pixel. The pixel is described by the format field, which tells us, how the pixel is organized in memory.

    The Remarks section of SDL_PixelFormat gives more information on the used datatype.

    The pitch field is basically the width of the surface multiplied by the size of the pixel (BytesPerPixel).

    With the function SDL_GetRGB, one can easily convert a pixel of any format to a RGB(A) triple/quadruple. SDL_MapRGB is the reverse of SDL_GetRGB, where one can specify a pixel as RGB(A) triple/quadruple to map it to the closest color specified by the format parameter.

    The SDL wiki provides many examples of the specific functions, i think you will find the proper examples to solve your problem.