博客园 首页 私信博主 显示目录 隐藏目录 管理 动画

运用C语言将图片转换成16进制的字符串(base64)

      最近在写手机端的性能测试脚本的时候,发现手机在上传图片数据时,先将图片转换成一堆16进制的字符,将字符传输过去,服务器再将字符解码成图片

我们在loadrunner中测试时,就需要用C语言将图片编码。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <io.h>
#include <fcntl.h>
#include <stdbool.h>

const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

char * base64_encode( 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 base64;
}

void encode(FILE * f_image, FILE * fp_out)
{
unsigned char bindata[2050]; //计算前的数据
char base64[4096]; //计算后的数据
size_t bytes; //计算前的数据实际的大小
while ( !feof( f_image ) )
{
bytes = fread( bindata, 1, 2049, f_image );
base64_encode( bindata, base64, bytes );
fprintf( fp_out, "%s", base64 );
}
}

//获取图片文件指针
FILE * f_image = fopen("C:\\Users\\Administrator\\Desktop\\image\\123.jpg", "rb");

//如果图片文件获取异常则直接 return 退出
if ( f_image == NULL )
{
fprintf(stderr, "Input file open error\n");
return EXIT_FAILURE;
}

encode(f_image, stdout);

//关闭图片文件指针
fclose(f_image);
f_image = NULL;

return 0;
}

 

posted @ 2017-10-27 21:08  空留  阅读(3504)  评论(2编辑  收藏  举报
作者:岩滨
出处:https://www.cnblogs.com/chenwenaa/

-------------------------------------------

个性签名:很多时候,我们想要的只是一个肯定的眼神和一颗理解的心!!!