使用C 代码将图片转换为 Base64 编码
时间: 2024-05-06 19:16:21 浏览: 9
以下是使用C语言实现将图片转换为Base64编码的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// Base64编码表
const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// 将3字节转换为4字节
void base64_encode(unsigned char *in, unsigned char *out, int len) {
int i, j;
unsigned char a, b, c;
for (i = 0, j = 0; i < len; i += 3, j += 4) {
a = in[i];
b = (i + 1 < len) ? in[i + 1] : 0;
c = (i + 2 < len) ? in[i + 2] : 0;
out[j + 0] = base64_table[a >> 2];
out[j + 1] = base64_table[((a & 0x03) << 4) | ((b & 0xf0) >> 4)];
out[j + 2] = (i + 1 < len) ? base64_table[((b & 0x0f) << 2) | ((c & 0xc0) >> 6)] : '=';
out[j + 3] = (i + 2 < len) ? base64_table[c & 0x3f] : '=';
}
}
int main(int argc, char **argv) {
if (argc != 3) {
printf("Usage: %s <input_file> <output_file>\n", argv[0]);
return 1;
}
// 读取输入文件
FILE *in_file = fopen(argv[1], "rb");
if (!in_file) {
printf("Error: Failed to open input file %s\n", argv[1]);
return 1;
}
fseek(in_file, 0, SEEK_END);
long in_size = ftell(in_file);
fseek(in_file, 0, SEEK_SET);
unsigned char *in_data = (unsigned char *)malloc(in_size);
fread(in_data, 1, in_size, in_file);
fclose(in_file);
// 计算输出缓冲区大小
int out_size = (int)(ceil(in_size / 3.0) * 4.0);
unsigned char *out_data = (unsigned char *)malloc(out_size);
// Base64编码
base64_encode(in_data, out_data, in_size);
// 写入输出文件
FILE *out_file = fopen(argv[2], "wb");
if (!out_file) {
printf("Error: Failed to open output file %s\n", argv[2]);
return 1;
}
fwrite(out_data, 1, out_size, out_file);
fclose(out_file);
// 释放内存
free(in_data);
free(out_data);
return 0;
}
```
使用方法:
```
$ ./base64_encode input.png output.txt
```
其中,`input.png`是要转换的图片文件名,`output.txt`是输出的Base64编码文件名。