Base64 图像编码不正确
Base64 Image encoding is incorrect
我正在尝试将.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;
}
}
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- Base64 图像编码不正确
- 由于alpha值的原因,将一个图像混合到另一个图像会产生不正确的图像
- MSVC UTF8字符串编码使用了不正确的代码点
- 使用图像 8UC1 c++ 的 unchar 垫正确打印不正确
- 图像过滤不正确
- 使用BruteForceMatcher或FlannBasedMatcher的KnnMatch进行的面部/图像匹配不正确
- 从图像中获得不正确的读数