c++ 实现图片转base64

原理:

原因:

网络传送渠道并不支持所有的字节,例如传统的邮件只支持可见字符的传送,像ASCII码的控制字符就不能通过邮件传送。这样用途就受到了很大的限制,比如图片二进制流的每个字节不可能全部是可见字符,所以就传送不了。最好的方法就是在不改变传统协议的情 况下,做一种扩展方案来支持二进制文件的传送。把不可打印的字符也能用可打印字符来表示,问题就解决了。Base64编码应运而生,Base64就是一种 基于64个可打印字符来表示二进制数据的表示方法。

2.base64编码原理

 Base64编码的思想是是采用64个基本的ASCII码字符对数据进行重新编码。它将需要编码的数据拆分成字节数组。以3个字节为一组。按顺序排列24 位数据,再把这24位数据分成4组,即每组6位。再在每组的的最高位前补两个0凑足一个字节。这样就把一个3字节为一组的数据重新编码成了4个字节。当所要编码的数据的字节数不是3的整倍数,也就是说在分组时最后一组不够3个字节。这时在最后一组填充1到2个0字节。

CString err;
    CFile ImageFile;

CFileException e;

//读取照片数据

{

//  ImageFile.Open(pInput,CFile::modeRead, &e);
if(!ImageFile.Open(pInput, CFile::modeRead,&e))
{
err.Format("ERROR:%s", pInput);
return err.AllocSysString();
}


    int iSrcLen = ImageFile.GetLength();
 
    unsigned char *szImageBin;
    szImageBin = new unsigned char[iSrcLen];
    ImageFile.Read((void*)szImageBin,iSrcLen);
 


    char *base64code;
    int nRemain = iSrcLen % 3;
    int nLeast= 0;
 
    if(nRemain != 0)
    {
        nLeast=1;
    }
    base64code = new char[(iSrcLen/3+nLeast)*4 + 1];    
 
CBase64 b64;
int dlen = b64.base64_encode2(szImageBin, iSrcLen, base64code);

base64code[dlen] = 0;

}

//转码

int CBase64::base64_encode2(const unsigned char *in, unsigned int inlen, char *out)
{
unsigned int i, j;


for (i = j = 0; i < inlen; i++) {
int s = i % 3; /* from 6/gcd(6, 8) */


switch (s) {
case 0:
out[j++] = base64en[(in[i] >> 2) & 0x3F];
continue;
case 1:
out[j++] = base64en[((in[i - 1] & 0x3) << 4) + ((in[i] >> 4) & 0xF)];
continue;
case 2:
out[j++] = base64en[((in[i - 1] & 0xF) << 2) + ((in[i] >> 6) & 0x3)];
out[j++] = base64en[in[i] & 0x3F];
}
}


/* move back */
i -= 1;
/* check the last and add padding */
if ((i % 3) == 0) {
out[j++] = base64en[(in[i] & 0x3) << 4];
out[j++] = BASE64_PAD;    BASE64_PAD   =
out[j++] = BASE64_PAD;
}
else if ((i % 3) == 1) {
out[j++] = base64en[(in[i] & 0xF) << 2];
out[j++] = BASE64_PAD;
}


return j;
}



猜你喜欢

转载自blog.csdn.net/xmmdbk/article/details/80108627