Skip to content

Instantly share code, notes, and snippets.

@igormorgado
Last active July 10, 2020 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igormorgado/8e678a28a914718a261ce40d51fffec0 to your computer and use it in GitHub Desktop.
Save igormorgado/8e678a28a914718a261ce40d51fffec0 to your computer and use it in GitHub Desktop.
int dump_texture_to_file(SDL_Renderer *renderer, SDL_Texture *texture, const char *filename)
{
SDL_Log("%s: ENTERING\n", __func__);
Uint32 format = 0;
int access = 0;
int width = 0;
int height = 0;
int retval = 0;
retval = SDL_QueryTexture(texture, &format, &access, &width, &height);
if (retval < 0)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"%s: SDL_QueryTexture(): %s", __func__, SDL_GetError());
return retval;
}
SDL_Log("%s: Texture info: Format: %s - Access: %d - Width: %d - Height: %d\n",
__func__, SDL_GetPixelFormatName(format), access, width, height);
Uint8 *pixels = malloc(width * height * SDL_BYTESPERPIXEL(format));
if(!pixels)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"%s: malloc(pixels): %s", __func__, SDL_GetError());
return retval;
}
SDL_RenderReadPixels(renderer, NULL, format, pixels, width * SDL_BYTESPERPIXEL(format));
if (retval < 0)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"%s: SDL_RenderReadPixels(): %s", __func__, SDL_GetError());
return retval;
}
SDL_Surface *surface = SDL_CreateRGBSurfaceWithFormatFrom(pixels, width, height, 32, width * SDL_BYTESPERPIXEL(format), format);
if(!surface)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"%s: SDL_CreateRGBSurfaceWithFormatFrom(): %s", __func__, SDL_GetError());
return -1;
}
SDL_Log("%s: Saving texture to file %s\n", __func__, filename);
SDL_SaveBMP(surface, filename);
if (retval < 0)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"%s: SDL_SaveBMP(): %s", __func__, SDL_GetError());
return retval;
}
free(pixels);
SDL_FreeSurface(surface);
SDL_Log("%s: LEAVING\n", __func__);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment