SDL2 C++ Taking a screenshot

user3371807 picture user3371807 · Mar 11, 2014 · Viewed 9.1k times · Source

Hi I would like to know if it is possible to simply take a screenshot with SDL2. I tried SDL_GetWindowSurface but I get an error saying:

No hardware accelerated renderers available.

I took the code from here.

Another solution I thought about is converting a texture to a surface but I didn't manage to do so...

Do you have any solution?

Answer

TalesM picture TalesM · Mar 12, 2014

It seems like you are mixing the rendering systems. That method will only work in the context of software rendering. For hardware rendering you should use the method SDL_RenderReadPixels(). To save the screenshot you would need a code like that:

SDL_Surface *sshot = SDL_CreateRGBSurface(0, w, h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);
SDL_RenderReadPixels(renderer, NULL, SDL_PIXELFORMAT_ARGB8888, sshot->pixels, sshot->pitch);
SDL_SaveBMP(sshot, "screenshot.bmp");
SDL_FreeSurface(sshot);

Where w and h are the screen width and height (you can get these values using SDL_GetRendererOutputSize()).