【问题标题】:How to load a base64 encoded image as a SDL texture in c++?如何在 C++ 中将 base64 编码图像加载为 SDL 纹理?
【发布时间】:2019-02-08 20:14:19
【问题描述】:

我从 cpprestsdk 获得一个 base64 编码的图像,并尝试在 sdl 窗口中显示它。

我无法从 base64 字符串创建表面,但它可以从磁盘上的文件中很好地工作。

我尝试了多次将字符串转换为 char 数组和向量,但 SDL_Surface 最后始终为空。

These 两个posts 引导我往 SDL_RWops 的方向前进:

SDL_Surface* base64ToSurface(std::string *image)
{
    SDL_RWops *rw = SDL_RWFromConstMem(image, sizeof(image));
    SDL_Surface *img = SDL_LoadBMP_RW(rw, 1);        
    if (img == nullptr)
    {
        logSDLError(std::cout, "base64ToSurface");
    }
    return img;
}

void convertBase64ToTexture()
{
    //base64 image string trimmed for a better readability
    std::string aImage = "R0lGODlhPQB...";

    SDL_Window *aWindow = SDL_CreateWindow("Lesson 2", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    SDL_Renderer *aRenderer = SDL_CreateRenderer(aWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    SDL_Surface *aSurface = base64ToSurface(&aImage);
    SDL_Texture *texture = nullptr;
    texture = SDL_CreateTextureFromSurface(aRenderer, aSurface);
    //Make sure converting went ok too
    if (texture == nullptr) 
    {
        logSDLError(std::cout, "CreateTextureFromSurface");
    }
}

【问题讨论】:

  • 那么...你的 base64 解码例程在哪里?现在看起来您只是将 base64 字节传递给 SDL_LoadBMP_RW() 并希望获得最好的结果。
  • 不仅如此,您还要求 SDL 将 std::string 对象(不是它包含的字符串,对象本身)的前 4/8 个字节解释为图像。那……行不通。
  • 我是 C++ 和 SDL 的新手,并尝试了多种解码字符串的方法。这个例子是为了简化设置。我没有通过广泛的谷歌研究找到帮助。我什至不确定是否可以从 base64 字符串在 sdl 中显示图像。
  • @Simon 你需要将decode base64 放入字节数组并传递该数组(连同它的长度!你的sizeof(image) 给你一个指针的大小,这与图像数据的大小无关) 到SDL_RWFromConstMem。例如。使用链接示例中的解码(我认为这不是最好的方法)std::vector<unsigned char> img_vec = base64_decode(aImage); SDL_RWops *rw = SDL_RWFromConstMem(&img_vec[0], img_vec.size());.

标签: c++ base64 sdl


【解决方案1】:

感谢您的帮助 keltar 立即帮助了我。如果您将您的评论添加为 answear,我会投票。

按照将 base64 jpg 加载到 sdl 窗口中的代码。

void LoadImageJpeg(std::wstring theImage, int x, int y)
{
    //Clear the window
    //SDL_RenderClear(renderer);
    std::vector<unsigned char> img_vec = base64_decode(theImage);
    SDL_RWops *rw = SDL_RWFromConstMem(&img_vec[0], img_vec.size());
    SDL_Surface *aSurface = IMG_LoadTyped_RW(rw, 1, "JPG");
    if (aSurface == nullptr) {
        logSDLError(std::cout, "base64ToSurface");
    }
    SDL_Texture *texture = nullptr;
    texture = SDL_CreateTextureFromSurface(renderer, aSurface);
    //Make sure converting went ok too
    if (texture == nullptr) {
        logSDLError(std::cout, "CreateTextureFromSurface");
    }
    renderTexture(texture, renderer, 0, 0);
    SDL_RenderPresent(renderer);
    //SDL_Delay(500);
}

谢谢。

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多