Skip to content

Instantly share code, notes, and snippets.

@DavidLudwig
Created April 19, 2014 16:09
Show Gist options
  • Save DavidLudwig/11088976 to your computer and use it in GitHub Desktop.
Save DavidLudwig/11088976 to your computer and use it in GitHub Desktop.
extern SDL_Renderer * _renderer;
static SDL_bool UI_SaveScreenshotBMP(const char * fileName)
{
int w = 0;
int h = 0;
SDL_GetWindowSize(_window, &w, &h);
const int bytesPerPixel = 4;
const int pitch = w * bytesPerPixel;
std::vector<Uint8> pixels(w * h * bytesPerPixel);
if (SDL_RenderReadPixels(_renderer, NULL, SDL_PIXELFORMAT_RGB888, &pixels[0], pitch) != 0) {
string errorMessage = string("Unable to read pixels, reason: ") + SDL_GetError();
SDL_SetError(errorMessage.c_str());
return SDL_FALSE;
}
SDL_Surface * screen = SDL_CreateRGBSurfaceFrom(
&pixels[0],
w, h,
bytesPerPixel * 8,
pitch,
0x00FF0000,
0x0000FF00,
0x000000FF,
0xFF000000);
if (!screen) {
string sdlError = SDL_GetError();
SDL_SetError("Unable to create SDL_Surface for output, reason: %s",
sdlError.c_str());
return SDL_FALSE;
}
if (SDL_SaveBMP(screen, fileName) != 0) {
string sdlError = SDL_GetError();
SDL_SetError("Unable to save BMP to file, \"%s\", reason: %s",
fileName, sdlError.c_str());
return SDL_FALSE;
}
SDL_Log("Saved screenshot to \"%s\".\n", fileName);
return SDL_TRUE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment