[英]Base64Encoding of UIImage Doesn't Match
I have a UIImage
and I want to encode it using base 64. I then send the string to our server. 我有一个
UIImage
,我想使用base 64对其进行编码。然后将字符串发送到我们的服务器。
Our server decodes it using btoa()
. 我们的服务器使用
btoa()
对其进行解码。 It can't do so properly. 它不能正确地这样做。
After debugging, we found out that the result of encoding/decoding using btoa()/atob()
does not match NSData's base64EncodedStringWithOptions
when I convert from UIImage to NSData and then encode. 调试之后,我们发现,当我从UIImage转换为NSData并进行编码时,使用
btoa()/atob()
进行编码/解码的结果与NSData的base64EncodedStringWithOptions
不匹配。
What's weird is they do match when I read the UIImage
directly as NSData
using dataWithContentsOfFile:
instead of converting from UIImage
to NSData
using UIImagePNGRepresentation()
奇怪的是,当我使用
dataWithContentsOfFile:
将UIImage
直接作为NSData
读取时,它们确实匹配dataWithContentsOfFile:
而不是使用UIImagePNGRepresentation()
从UIImage
转换为NSData
My problem is that I'm supposed to use an imagepicker
that returns a UIImage
. 我的问题是我应该使用
imagepicker
返回一个UIImage
。 I don't want to write the image to file and then read it directly as NSData
. 我不想将图像写入文件,然后直接将其读取为
NSData
。 it's not efficient. 效率不高。 Is there a way to solve this?
有办法解决吗?
Try this for base64 encoding: 尝试以下方法进行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.