将 BGR 图像转换为 jpeg 格式的 base64 字符串
Convert BGR image into base64 string as jpeg
我有以OpenCV约定表示的彩色图像,其中每个像素都以BGR顺序一行又一行地表示为unsigned char
:
const int BGR = 3;
const int rows= 256;
const int cols = 512;
unsigned char rawIm[BGR * rows *cols] = {'g', 't', 'y', // lots of chars.....}
我想将此流转换为表示相应 jpeg 图像的 base64 字符串,而无需实际将图像写入磁盘,只是"纯"字节转换。 如何在C++中做到这一点?
对于图像到jpeg部分,您可以使用toojpeg,它比libjpeg更容易使用。 https://create.stephan-brumme.com/toojpeg/
但是您必须先将 BGR 反转为 RGB,因为 toojpeg 还不支持 BGR。
下面是一个示例:
#include <vector>
#include <string>
#include <iostream>
#include "toojpeg.h"
std::vector<unsigned char> jpeg_data;
void myOutput(unsigned char byte) {
jpeg_data.push_back(byte);
}
int main() {
const auto width = 800;
const auto height = 600;
const auto bytesPerPixel = 3;
unsigned char bgr_data[width * height * bytesPerPixel];
// put some sample data in bgr_data, just for the example
for (unsigned i = 0; i < sizeof(bgr_data); i += 3) {
bgr_data[i] = i / width;
bgr_data[i + 1] = i / width * 2;
bgr_data[i + 2] = i / width * 3;
}
// convert BGR to RGB
unsigned char rgb_data[sizeof(bgr_data)];
for (unsigned i = 0; i < sizeof(bgr_data); i += 3) {
rgb_data[i] = bgr_data[i + 2];
rgb_data[i + 1] = bgr_data[i + 1];
rgb_data[i + 2] = bgr_data[i];
}
// convert the RGB data to jpeg
bool isRGB = true;
const auto quality = 90;
const bool downsample = false;
const char* comment = "example image";
bool result_ok = TooJpeg::writeJpeg(myOutput, rgb_data, width, height, isRGB, quality, downsample, comment);
if (result_ok) {
// jpeg_data now contains jpeg-encoded image, which can be encoded as base 64
}
return 0;
}
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 将"打开的CV图像"中的"颜色"转换为整数格式
- TDateTime格式在C++Builder中不会更改
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 检查不带转换的扫描格式
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- 无法解码base64+deflate数据
- 是否可以从格式字符串中检索"width"
- clang格式:宏的缩进
- clang格式:禁用排序包含
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 将RGB图像保存为PPM格式
- 询问在设计我的手臂模拟器功能表示格式1
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 带有Protobuf序列化的C++Hazelcast:字符串不是UTF-8格式的
- 如何将strftime中的格式错误作为异常捕获
- 将CHW格式的浮点向量转换为cv::Mat
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 如何以叮当格式设置评论的行长?
- 将 BGR 图像转换为 jpeg 格式的 base64 字符串