将BGR图片转换为jpeg的base64字符串

问题描述 投票:0回答:1

我有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 ++中做到这一点?

c++ base64 jpeg tobase64string
1个回答
0
投票

对于要转换为jpeg的图像,您可以使用toolibeg,它比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;
}

© www.soinside.com 2019 - 2024. All rights reserved.