c++实现Mat和字节流、Base64的互转
·
base64编码简单介绍
- 意义:Base64编码的并不是对数据进行加密,而是为了避免传输数据时的编码错误。数据使用ascii码传输时,可见字符的组合范围是65到90代表大写的字母A-Z,而组合128~255是不可见字符。在网络上交换数据时,往往要经过多个设备,由于不同的设备对字符的处理方式有一些不同,这样那些不可见字符就有可能被处理错误,这是不利于传输的。所以就先把数据先做一个Base64编码,统统变成可见字符,这样出错的可能性就大降低了。
- 特点:
- 标准base64只有64个字符(英文大小写、数字和+、/)以及用作后缀等号;
- .base64是把3个字节变成4个可打印字符,所以base64编码后的字符串一定能被4整除;
- base64可以归类为一种对称加密,但由于其密钥即转换方式是公开的,因此实际上几乎没有加密效果,只能用于编码转换。
代码实现
- 验证base64与图片准确性的在线网站 https://www.base64decode.org/
- base64实现的 c++代码库
- mat互转代码
#include <stdlib.h> #include <string.h> #include "opencv2/opencv.hpp" #include "base64.h" //imgType 包括png bmp jpg jpeg等opencv能够进行编码解码的文件 std::string Mat2Base64(const cv::Mat &image, std::string imgType) { //Mat转base64 std::vector<uchar> buf; cv::imencode(imgType, image, buf); //uchar *enc_msg = reinterpret_cast<unsigned char*>(buf.data()); std::string img_data = base64_encode(buf.data(), buf.size(), false); return img_data; } cv::Mat Base2Mat(std::string &base64_data) { cv::Mat img; std::string s_mat; s_mat = base64_decode(base64_data.data(), false); std::vector<char> base64_img(s_mat.begin(), s_mat.end()); img = cv::imdecode(base64_img, cv::IMREAD_COLOR); //CV::IMREAD_UNCHANGED return img; } int main(){ cv::Mat image = cv::imread("./test.jpg"); if(image.empty()){ std::cerr << "ERROR! Unable to open image\n"; return -1; } std::string img_data = Mat2Base64(image,".jpg"); printf("%s\n", img_data.c_str()); cv::Mat dest = Base2Mat(img_data); cv::imshow("img", dest); cv::waitKey(0); return 0; }- 图像字节数组转base64字符串,先转mat,后编码base64
#include <stdlib.h> #include <string.h> #include <iostream> #include <fstream> #include "opencv2/opencv.hpp" #include "base64.h" using namespace std; int main(){ bool bgr = true; int height = 1080; int width = 1920; unsigned char* rgb_buffer = (unsigned char *)malloc((height * width * 3) * sizeof(unsigned char)); memset(rgb_buffer, 0, (height * width * 3) * sizeof(unsigned char)); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { rgb_buffer[(i * width + j) * 3 + 2] = 127; // blue value assign to 127 //ToDo //your process function } } } //the opencv mat constructors must be permutation BGR or BGRA orders //这一步实现了字节流转Mat cv::Mat source(height, width, CV_8UC3, pBuff); free(pBuff); pBuff = NULL; cv::Mat image; if (bgr) { source= image.clone(); } else { cv::cvtColor(source, image, cv::COLOR_RGB2BGR); //cv::COLOR_RGBA2BGRA } std::vector<uchar> buf; cv::imencode(".png", image, buf); uchar *enc_msg = reinterpret_cast<unsigned char*>(buf.data()); std::string encoded = base64_encode(enc_msg, buf.size(), false); ofstream out; out.open("base64_str", ios::out | ios::trunc); out << encode_str << endl; out.close(); }
更多推荐
所有评论(0)