小编Ror*_*ngs的帖子

从 Base64 C++ 解码并保存图像文件

我正在尝试用 C++ 编写一个程序,该程序可以将图像编码为 Base64,也可以将 Base64 解码为图像。我相信编码器功能工作正常,有些网站可以采用我生成的 Base64 代码并将其解码为图像,但由于某种原因,一旦我将 Base64 解码为字符串,然后将其写入文件并将其另存为png 它说它无法在图像查看器中打开。

我确认写入新文件的字符串与现有文件完全相同(在文本编辑器中打开时),但由于某种原因,新文件无法打开,但现有文件可以打开。我什至尝试在文本编辑器中创建一个新文件,并将旧文件中的文本复制到其中,但它仍然无法在图像查看器中打开。

我相信编码函数和 base64 解码函数都可以正常工作。我认为问题出在图像解码功能上。

图像编码功能

string base64_encode_image(const string& path) {
    vector<char> temp;

    std::ifstream infile;
    infile.open(path, ios::binary);     // Open file in binary mode
    if (infile.is_open()) {
        while (!infile.eof()) {
            char c = (char)infile.get();
            temp.push_back(c);
        }
        infile.close();
    }
    else return "File could not be opened";
    string ret(temp.begin(), temp.end() - 1);
    ret = base64_encode((unsigned const char*)ret.c_str(), ret.size());

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

图像解码功能

void base64_decode_image(const string& input) {
    ofstream outfile;
    outfile.open("test.png", ofstream::out);

    string temp …
Run Code Online (Sandbox Code Playgroud)

c++ base64 png jpeg image

4
推荐指数
1
解决办法
4984
查看次数

标签 统计

base64 ×1

c++ ×1

image ×1

jpeg ×1

png ×1