C snippets: base64编码二进制文件(测试jpg图片)

如下是编码接口:

const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char *base64_encode_file(const unsigned char * bindata, char * base64, int binlength)
{
    int i, j;
    unsigned char current;
 
    for ( i = 0, j = 0 ; i < binlength ; i += 3 )
    {
        current = (bindata[i] >> 2) ;
        current &= (unsigned char)0x3F;
        base64[j++] = base64char[(int)current];
 
        current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;
        if ( i + 1 >= binlength )
        {
            base64[j++] = base64char[(int)current];
            base64[j++] = '=';
            base64[j++] = '=';
            break;
        }
        current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );
        base64[j++] = base64char[(int)current];
 
        current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;
        if ( i + 2 >= binlength )
        {
            base64[j++] = base64char[(int)current];
            base64[j++] = '=';
            break;
        }
        current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );
        base64[j++] = base64char[(int)current];
 
        current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;
        base64[j++] = base64char[(int)current];
    }
    base64[j] = '\0';
    return 0;
}

测试程序:将一个jpg文件进行base64编码

unsigned int imageSize;
unsigned char *imageBin;
char *imageBase64;
size_t result;
unsigned int base64StrLength;

FILE *fp = NULL;
fp = fopen("test.jpg", "rb");   //待编码图片
if (NULL == fp)
{
    printf("file open failed\n");
    return -1;
}
//获取图片大小
fseek(fp, 0L, SEEK_END);
imageSize = ftell(fp);
fseek(fp, 0L, SEEK_SET);

//分配内存存储整个图片
imageBin = (unsigned char *)malloc(sizeof(unsigned char)*imageSize);
if (NULL == imageBin)
{
    printf("malloc failed\n");
    return -1;
}

//读取图片
result = fread(imageBin, 1, imageSize, fp);
if (result != imageSize)  
{  
    printf("file read failed\n");  
    return -1;
}  
fclose(fp);

//分配编码后图片所在buffer
imageBase64 = (char *)malloc(sizeof(char)*imageSize*2);//因为编码一版会比源数据大1/3的样子,这里直接申请源文件一倍的空间
if (NULL == imageBase64)
{
    printf("malloc failed\n");
    return -1;
}
//base64编码
base64_encode_file(imageBin, imageBase64, imageSize);

// imageBase64 即为base64编码后的图片字符串

free(imageBin);
free(imageBase64);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值