運用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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM