[英]Base64Encoding of UIImage Doesn't Match
我有一個UIImage
,我想使用base 64對其進行編碼。然后將字符串發送到我們的服務器。
我們的服務器使用btoa()
對其進行解碼。 它不能正確地這樣做。
調試之后,我們發現,當我從UIImage轉換為NSData並進行編碼時,使用btoa()/atob()
進行編碼/解碼的結果與NSData的base64EncodedStringWithOptions
不匹配。
奇怪的是,當我使用dataWithContentsOfFile:
將UIImage
直接作為NSData
讀取時,它們確實匹配dataWithContentsOfFile:
而不是使用UIImagePNGRepresentation()
從UIImage
轉換為NSData
我的問題是我應該使用imagepicker
返回一個UIImage
。 我不想將圖像寫入文件,然后直接將其讀取為NSData
。 效率不高。 有辦法解決嗎?
嘗試以下方法進行base64編碼:
+ (NSString*)base64forData:(NSData*)theData
{
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.