c++ - 将 SDL_Surface 像素复制到 STL 容器中

标签 c++ sdl pixel-manipulation

我写了这个我想在程序中使用的函数,但由于某种原因,尽管没有出错,它还是失败了:

std::deque <std::deque <bool> > load_image(std::string & image_name){
    SDL_Surface * image = open_image(image_name);
    if (!image)
        exit(3);
    Uint32 * pixels = (Uint32 *) image -> pixels;
    std::deque <std::deque <bool> > grid(HEIGHT, std::deque <bool>(WIDTH, false));
    for(int y = 0; y < std::min(image -> h, HEIGHT); y++)
        for(int x = 0; x < std::min(image -> w, WIDTH); x++)
            grid[y][x] = (pixels[(image -> w * y) + x] == 0);
    SDL_FreeSurface(image);
    return grid;
}

我只是想将像素是否为黑色复制到 grid 中。当我分别运行 grid[y][x](pixels[(image -> w * y) + x] == 0) 时,程序运行正常。当我执行 grid[y][x] = (pixels[(image -> w * y) + x] == 0); 时,程序在图像中间的某处崩溃。

我很确定 (image -> w * y) + x 得到正确的像素,无论 xy 是什么仅限于,所以我没有看到什么??

最佳答案

the program crashes somewhere in the middle of the image.

你忘了说是读内存还是写内存崩溃了。您也可以尝试调试它 - 通过 VisualStudio/gdb 或将 yx 的值转储到 stderr/OutputDebugString.

grid[y][x] = (pixels[(image -> w * y) + x] == 0);

没有。

解决单像素使用问题:

&((const char*)image->pixels)[y * image->pitch + x*image->format->BytesPerPixel];

(const Uint32*)((const char*)image->pixels + y * image->pitch + x*image->format->BytesPerPixel)

不保证 Pixel 是 32 位的。此外,如果这不是软件表面,则需要将其锁定。请参阅 SDL_Surface 的文档和 SDL_PixelFormat

关于c++ - 将 SDL_Surface 像素复制到 STL 容器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8902357/

相关文章:

c++ - 部分特化可以在特化的参数列表中引用 sizeof(T) 吗?

compiler-errors - 使用SDL和g++编译找不到-lSDLmain等

c - SDL_init() 导致 c 文件不输出任何内容

c++ - STL 集中的指针委托(delegate)

c++ - 为测试目的分配 argv

javascript - 绘制饱和度/亮度渐变

python - 在python中更快的图像像素处理

javascript - 直接在 Canvas 上设置路径的 alpha channel 中的每个点

c++ - 我怎样才能找到 DirectShow 过滤器的 clsid?

image - "Undefined Reference To ' IMG_Load '"代码块和 SDL_Image 错误