以下是使用libjpeg库和base64库实现jpg图片转base64的C++代码:

#include <stdio.h>
#include <stdlib.h>
#include <jpeglib.h>
#include <string.h>
#include "base64.h"

void jpegToBase64(char* inputPath, char* outputPath) {

    // 读取JPEG文件
    FILE* infile = fopen(inputPath, "rb");
    if (!infile) {
        fprintf(stderr, "无法读取JPEG文件 %s\n", inputPath);
        exit(EXIT_FAILURE);
    }

    // 初始化JPEG解压缩对象
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    cinfo.err = jpeg_std_error(&jerr);
    jpeg_create_decompress(&cinfo);
    jpeg_stdio_src(&cinfo, infile);

    // 读取JPEG文件头信息,设置解压参数
    jpeg_read_header(&cinfo, TRUE);
    jpeg_start_decompress(&cinfo);

    // 读取JPEG图片数据
    unsigned char* buffer = (unsigned char*)malloc(cinfo.output_width * cinfo.output_height * cinfo.output_components);
    unsigned char* rowptr;
    while (cinfo.output_scanline < cinfo.output_height) {
        rowptr = buffer + cinfo.output_scanline * cinfo.output_width * cinfo.output_components;
        jpeg_read_scanlines(&cinfo, &rowptr, 1);
    }

    // 关闭JPEG解压缩对象和文件
    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
    fclose(infile);

    // 将JPEG图片数据编码为Base64字符串
    char* base64str = base64_encode(buffer, cinfo.output_width * cinfo.output_height * cinfo.output_components);
    free(buffer);

    // 将Base64字符串写入文件
    FILE* outfile = fopen(outputPath, "wb");
    if (!outfile) {
        fprintf(stderr, "无法写入Base64文件 %s\n", outputPath);
        exit(EXIT_FAILURE);
    }
    fwrite(base64str, strlen(base64str), 1, outfile);
    fclose(outfile);

    // 释放Base64字符串内存
    free(base64str);

    printf("图片 %s 转换为Base64成功,输出到文件 %s\n", inputPath, outputPath);
}

int main(int argc, char** argv) {

    if (argc != 3) {
        fprintf(stderr, "使用方法:jpgToBase64 input.jpg output.txt\n");
        exit(EXIT_FAILURE);
    }

    jpegToBase64(argv[1], argv[2]);

    return 0;
}

注意:以上代码需要与libjpeg和base64库链接,编译命令如下:

g++ -o jpgToBase64 jpgToBase64.cpp -ljpeg -lbase64
``
用c++写jpg图片转base64的代码

原文地址: https://www.cveoy.top/t/topic/e244 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录