Base64 图像编码不正确

Base64 Image encoding is incorrect

本文关键字:不正确 图像编码 Base64      更新时间:2023-10-16

我正在尝试将.jpg文件转换为 base64 然后转换为 svg 文件,但我的 base64 是错误的我不知道我是否做了明显错误的事情这是我第一次在 c++ 中使用 base64

当我运行代码时,我得到一个格式正确和正确填充的 svg 文件,但当我打开它时该文件是空白的。

这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include "base64.h"
#include "base64.cpp"
int main()
{
bool url;
std::string image;
std::string encoded;
std::string alldata = "";
std::cout << "Name of file without extension: n";
std::cin >> image;
// Takes the name of the image
std::string outfile = image + ".svg";
// creates outfiles
image = image + ".jpg";
// adds jpg extension to name of file
std::string line;
std::ifstream input(image, std::ios::in | std::ios::binary);
// opens the image
if (input.is_open()) {
// checks if the file is open
while (getline(input, line)) {
//  std::string encoded = base64_encode_mime(const& s);
alldata = alldata + (line.c_str());
// makes multiple lines into one
}
input.close();
}
else {
std::cout << "ERROR: File not found";
}
encoded = base64_encode(reinterpret_cast<const unsigned char*>(alldata.c_str()), alldata.length(), url = false);
// encodes the one line of image data
std::string svg;
std::ofstream output(outfile,std::ios::binary|std::ios::out);
svg = "<?xml version='1.0' encoding='UTF-8' standalone='no'?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg version='1.1' id='Layer_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='1920px' height='1200px' viewBox='0 0 1920 1200' enable-background='new 0 0 1920 1200' xml:space='preserve'>  <image id='image0' width='1920' height='1200' x='0' y='0' href='data:image/png;base64,";
svg = svg + encoded;
svg = svg + "'/> </svg>";
output << svg;
}

我正在使用René Nyffenegger的base64库,在这里找到:https://github.com/ReneNyffenegger/cpp-base64/blob/master/base64.cpp 我已经测试了这个库,它似乎可以正确编码文本。

您的错误在于您从文件中读取数据的方式。不要在二进制文件上使用getline,除此之外,它不会将换行符返回给您。第二个问题是,通过在附加每一行时使用c_str(),您假设数据中不会有空字符,这不太可能是真的。

最简单的方法是一次读取一个字符的文件

if (input.is_open()) {
char ch;
while (input.get(ch)) {
alldata += ch;
}
}