gpt4 book ai didi

c++ - 如何在 SDL 2 中获取并保存 BMP 屏幕截图?

转载 作者:IT老高 更新时间:2023-10-28 22:37:08 25 4
gpt4 key购买 nike

仅使用给定的 SDL_Window* 和 SDL_Renderer*,我如何在 SDL 2.0 中创建和保存屏幕截图?

最佳答案

下面是一个将屏幕截图保存在 SDL 2 中的函数,该屏幕截图取 self 目前正在编写的库。

bool saveScreenshotBMP(std::string filepath, SDL_Window* SDLWindow, SDL_Renderer* SDLRenderer) {
SDL_Surface* saveSurface = NULL;
SDL_Surface* infoSurface = NULL;
infoSurface = SDL_GetWindowSurface(SDLWindow);
if (infoSurface == NULL) {
std::cerr << "Failed to create info surface from window in saveScreenshotBMP(string), SDL_GetError() - " << SDL_GetError() << "\n";
} else {
unsigned char * pixels = new (std::nothrow) unsigned char[infoSurface->w * infoSurface->h * infoSurface->format->BytesPerPixel];
if (pixels == 0) {
std::cerr << "Unable to allocate memory for screenshot pixel data buffer!\n";
return false;
} else {
if (SDL_RenderReadPixels(SDLRenderer, &infoSurface->clip_rect, infoSurface->format->format, pixels, infoSurface->w * infoSurface->format->BytesPerPixel) != 0) {
std::cerr << "Failed to read pixel data from SDL_Renderer object. SDL_GetError() - " << SDL_GetError() << "\n";
delete[] pixels;
return false;
} else {
saveSurface = SDL_CreateRGBSurfaceFrom(pixels, infoSurface->w, infoSurface->h, infoSurface->format->BitsPerPixel, infoSurface->w * infoSurface->format->BytesPerPixel, infoSurface->format->Rmask, infoSurface->format->Gmask, infoSurface->format->Bmask, infoSurface->format->Amask);
if (saveSurface == NULL) {
std::cerr << "Couldn't create SDL_Surface from renderer pixel data. SDL_GetError() - " << SDL_GetError() << "\n";
delete[] pixels;
return false;
}
SDL_SaveBMP(saveSurface, filepath.c_str());
SDL_FreeSurface(saveSurface);
saveSurface = NULL;
}
delete[] pixels;
}
SDL_FreeSurface(infoSurface);
infoSurface = NULL;
}
return true;
}

干杯!-尼尔

关于c++ - 如何在 SDL 2 中获取并保存 BMP 屏幕截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20233469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com