SDL 访问 SDL_Surface 的像素数据

SDL accessing pixel data of SDL_Surface

我想操纵加载图像的颜色,但在尝试备份像素数据时遇到问题。我的代码看起来像这样:

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
    }
}

我可以通过将 oriPixels 更改为 Uint32 向量来使代码正常工作,而且我在这样做时没有遇到任何问题(可以使用 oriPixels 将图像恢复为原始颜色)。

我应该怎么做才能正确加载像素数据?

图像是 32 位的。

您必须考虑数据对齐。可以根据表面格式填充行。 查看有关 SDL_Surface 的音高字段的文档以获取更多详细信息 https://wiki.libsdl.org/SDL_Surface

您遇到访问冲突是因为内存缓冲区大小不是宽度 * 高度,而是实际间距 * 高度。