Base64UIImage的编码不匹配



我有一个UIImage,我想用base 64对其进行编码。然后我把字符串发送到我们的服务器。

我们的服务器使用 btoa() 对其进行解码。它不能正确地做到这一点。

调试后,我们发现使用btoa()/atob()进行编码/解码的结果与 NSData 从 UIImage 转换为 NSData 然后进行编码时的base64EncodedStringWithOptions不匹配。

奇怪的是,当我使用dataWithContentsOfFile:直接阅读UIImage时,它们确实匹配NSData,而不是使用UIImagePNGRepresentation()UIImage转换为NSData

我的问题是我应该使用返回UIImageimagepicker。我不想将图像写入文件,然后直接读取它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] ;
}

最新更新