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);

你可能感兴趣的:(Linux,C/C++)