我写了这个我想在程序中使用的函数,但由于某种原因,尽管没有出错,它还是失败了:
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
得到正确的像素,无论 x
和 y
是什么仅限于,所以我没有看到什么??
最佳答案
the program crashes somewhere in the middle of the image.
你忘了说是读内存还是写内存崩溃了。您也可以尝试调试它 - 通过 VisualStudio/gdb 或将 y
和 x
的值转储到 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/