简体   繁体   中英

SDL accessing pixel data of SDL_Surface

I want to manipulate the color of loaded images but I am having trouble when I try to backup the pixel data. My code looks something like this:

Uint32* pixels, oriPixels;
SDL_Surface* image;

void BackupPixelData()
{
    pixels = (Uint32*)image->pixels;
    oriPixels = new Uint32[image->w * image->h];
    for (int i = 0; i < image->w * image->h; i++)
    {
        oriPixels[i] = pixels[i]; //This causes an access violation midway through
        *(oriPixels + i) = *(pixels + i); //Using this method does not cause any crash, but the image will have artifacts
    }
}

I can get the code to work by changing oriPixels into a vector of Uint32, and I haven't experienced any issues doing that (the image can be restored to the original color using the oriPixels).

What should I do to properly load the pixel data?

The image is in 32 bits.

You must take into account data alignment. Rows may be padded depending on the surface format. Check the documentation about the pitch field of the SDL_Surface for more details https://wiki.libsdl.org/SDL_Surface .

You get the access violation because the memory buffer size is not width * height but actually pitch * height.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM