c++ 将base64 转为图像 并创建一个窗口展示出来 不使用qt
时间: 2023-12-29 14:05:39 浏览: 30
要将base64编码的字符串转换为图像,我们需要进行以下步骤:
1. 将base64编码的字符串解码为二进制数据。
2. 将二进制数据写入到一个文件中,可以使用C++的标准文件流完成。
3. 使用第三方库(如OpenCV)读取文件并将其解码为图像。
4. 创建一个窗口,将图像展示出来。
以下是一个示例代码,演示如何将base64编码的字符串转换为图像并展示出来。请注意,此代码使用OpenCV库来处理图像。
```c++
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <openssl/bio.h>
#include <openssl/evp.h>
using namespace std;
using namespace cv;
// 解码 base64 编码的字符串
string base64_decode(const string& encoded_string) {
BIO *bio, *b64;
char decoded_buffer[encoded_string.size()];
memset(decoded_buffer, 0, sizeof(decoded_buffer));
bio = BIO_new_mem_buf(encoded_string.c_str(), -1);
b64 = BIO_new(BIO_f_base64());
bio = BIO_push(b64, bio);
int length = BIO_read(bio, decoded_buffer, encoded_string.size());
BIO_free_all(bio);
return string(decoded_buffer, length);
}
int main() {
// 从 base64 编码的字符串中获取图像数据
string base64_string = "iVBORw0KGgoAAAANSUhEUgAAAAUA";
string decoded_string = base64_decode(base64_string);
const char* data = decoded_string.c_str();
// 将二进制数据写入文件中
ofstream image_file("image.png", ios::out | ios::binary);
image_file.write(data, decoded_string.size());
image_file.close();
// 使用 OpenCV 读取图像
Mat img = imread("image.png", IMREAD_UNCHANGED);
// 创建并展示窗口
namedWindow("Image", WINDOW_NORMAL);
imshow("Image", img);
waitKey(0);
return 0;
}
```
请注意,这段代码使用了OpenSSL库来进行base64解码,需要在编译时链接该库。如果您使用的是Linux系统,则可以使用以下命令进行编译:
```
g++ main.cpp -o main -lopencv_core -lopencv_highgui -lopencv_imgproc -lcrypto
```
在Windows系统上,您需要在编译器中添加OpenSSL库的链接库文件。