2012-11-21 152 views
-2

我想將圖像加密成Base64字符串。請找到所需的代碼。我得到空值作爲響應使用Base64編碼圖像的空值

fullpath = /Users/srt/Library/Application Support/iPhone Simulator/5.1/Applications//Documents/image.png 



UIImage *sImage=[UIImage imageNamed:fullPath]; 
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; 
    NSLog(@"image saved"); 
    NSLog(@"%@",fullPath); 
    NSData* data = UIImageJPEGRepresentation(sImage, 1.0f); 


    NSString *strEncoded = [self Base64ImageEncode:data]; 
    NSLog(@"This is the encryption %@ ",strEncoded); 

-(NSString *)Base64ImageEncode:(NSData *)data{ 
    //Point to start of the data and set buffer sizes 
    int inLength = [data length]; 
    int outLength = ((((inLength * 4)/3)/4)*4) + (((inLength * 4)/3)%4 ? 4 : 0); 
    const char *inputBuffer = [data bytes]; 
    char *outputBuffer = malloc(outLength); 
    outputBuffer[outLength] = 0; 

    //64 digit code 
    static char Encode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/"; 

    //start the count 
    int cycle = 0; 
    int inpos = 0; 
    int outpos = 0; 
    char temp; 

    //Pad the last to bytes, the outbuffer must always be a multiple of 4 
    outputBuffer[outLength-1] = '='; 
    outputBuffer[outLength-2] = '='; 

    /* http://en.wikipedia.org/wiki/Base64 
    Text content M   a   n 
    ASCII   77   97   110 
    8 Bit pattern 01001101 01100001 01101110 

    6 Bit pattern 010011 010110 000101 101110 
    Index   19  22  5  46 
    Base64-encoded T  W  F  u 
    */ 


    while (inpos < inLength){ 
     switch (cycle) { 
      case 0: 
       outputBuffer[outpos++] = Encode[(inputBuffer[inpos]&0xFC)>>2]; 
       cycle = 1; 
       break; 
      case 1: 
       temp = (inputBuffer[inpos++]&0x03)<<4; 
       outputBuffer[outpos] = Encode[temp]; 
       cycle = 2; 
       break; 
      case 2: 
       outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xF0)>> 4]; 
       temp = (inputBuffer[inpos++]&0x0F)<<2; 
       outputBuffer[outpos] = Encode[temp]; 
       cycle = 3; 
       break; 
      case 3: 
       outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xC0)>>6]; 
       cycle = 4; 
       break; 
      case 4: 
       outputBuffer[outpos++] = Encode[inputBuffer[inpos++]&0x3f]; 
       cycle = 0; 
       break; 
      default: 
       cycle = 0; 
       break; 
     } 
    } 
    NSString *pictemp = [NSString stringWithUTF8String:outputBuffer]; 
    free(outputBuffer); 
    return pictemp; 
} 

編碼的結果是This is the encryption請糾正我,我的錯誤和原因還,如果需要或任何其他更好的辦法做到這一點。

+0

什麼是fullPath? –

+0

圖像存儲的位置。 – onkar

+0

你可以請帖路徑? –

回答

2

使用imageNamed:方法無法從文檔目錄加載圖像。 此方法用於從應用程序包中加載圖像。參數應該是圖像的名稱。

像:

UIImage *tempImage = [UIImage imageNamed:@"myImage.png"]; 

這就是爲什麼像越來越空。

使用imageWithContentsOfFile:方法。

UIImage *sImage = [UIImage imageWithContentsOfFile:fullPath]; 
+0

謝謝。還是相同的迴應 – onkar

+0

@onkar:請把斷點和檢查sImage和數據是否存在,或者它是空的。 –