将 SDL 纹理保存到文件 [英] Save SDL Texture to file

查看:78
本文介绍了将 SDL 纹理保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将纹理保存到 png 中,而我唯一得到的是是屏幕的一部分的屏幕截图.

I am trying to save a texture to a png and the only thing I'm getting is a screenshot of a portion of the screen.

我的代码示例:

src_texture =  SDL_CreateTextureFromSurface( renderer, some_surface );
/*.........*/

/*create target texture */
SDL_Texture *tmp_texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_TARGET , w, h);
SDL_SetTextureBlendMode(tmp_texture, SDL_BLENDMODE_NONE);
SDL_SetRenderTarget(renderer, tmp_texture);
SDL_RenderCopy(renderer, src_texture, NULL, NULL);

/*create surface and get pixels from texture*/
PixelFormat mask = GetMask(format);
s = SDL_CreateRGBSurface(0, w, h, 32, mask.Rmask, mask.Gmask, mask.Bmask, mask.Amask);
if (s) {
    SDL_SetRenderTarget(renderer, tmp_texture);
    SDL_RenderReadPixels(renderer, NULL, s->format->format, s->pixels, s->pitch);
    IMG_SavePNG(s, "image.png");

}
SDL_DestroyTexture(tmp_texture);

知道如何实现这一目标吗?

Any idea how to achieve this?

推荐答案

这是我的解决方案:

void save_texture(const char* file_name, SDL_Renderer* renderer, SDL_Texture* texture) {
    SDL_Texture* target = SDL_GetRenderTarget(renderer);
    SDL_SetRenderTarget(renderer, texture);
    int width, height;
    SDL_QueryTexture(texture, NULL, NULL, &width, &height);
    SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0);
    SDL_RenderReadPixels(renderer, NULL, surface->format->format, surface->pixels, surface->pitch);
    IMG_SavePNG(surface, file_name);
    SDL_FreeSurface(surface);
    SDL_SetRenderTarget(renderer, target);
}

这个函数在文件写入之外没有副作用.这使得插入变得容易,因为您不必担心渲染目标会被破坏.随意添加您认为合适的错误处理.

This function has no side effects outside of the file write. This makes it easy to insert as you don't have to worry that the render target will be clobbered. Feel free to add error handling as you see fit.

这篇关于将 SDL 纹理保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆