以下是C语言实现本地图片的base64编码并输出的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: ./base64_encode [filename]\n");
return 1;
}
char *filename = argv[1];
FILE *fp = fopen(filename, "rb");
if (!fp) {
printf("Error: Can't open file %s.\n", filename);
return 1;
}
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *data = (char *) malloc(file_size + 1);
fread(data, file_size, 1, fp);
fclose(fp);
BIO *b64 = BIO_new(BIO_f_base64());
BIO *bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_write(bio, data, file_size);
BIO_flush(bio);
char outbuf[BUF_SIZE] = { 0 };
int outlen = 0;
do {
memset(outbuf, 0, BUF_SIZE);
outlen = BIO_read(bio, outbuf, BUF_SIZE);
if (outlen > 0) {
printf("%s", outbuf);
}
} while (outlen > 0);
BIO_free_all(bio);
free(data);
return 0;
}
需要注意的是,该代码引用了OpenSSL库进行base64编码,因此需要在编译时链接OpenSSL库,例如:
gcc -o base64_encode base64_encode.c -lssl -lcrypto
执行程序时,需要传入待编码的文件名作为参数,例如:
./base64_encode image.jpg
将会输出编码后的字符串。如果需要将输出结果保存到文件中,可以使用重定向符:
./base64_encode image.jpg > output.txt